Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReorderableListView does not identify keys in Custom Widget

Tags:

flutter

dart

I have a ReorderableListView which should populate custom widget, however even with keys passed in custom stateless widget class and constructor, I get the following error:

All children of this widget must have a key. 'package:flutter/src/material/reorderable_list.dart': Failed assertion: line 71 pos 10: 'children.every((Widget w) => w.key != null)'

Here is the dart code:

class CustomWidget extends StatelessWidget{

  String CustomWidgetString;
  String WidgetKey;

  CustomWidget({this.CustomWidgetString, this.WidgetKey});

  Widget _widget(){
    return Text(
      CustomWidgetString,
      key: Key(WidgetKey),
    );
  }

  @override
  Widget build(BuildContext context){
    return _widget();
  }
}


class AppState extends State<App>{

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: Text("Reorderable List"),
      ),
      body: ReorderableListView(
        scrollDirection: Axis.vertical,
        children: <Widget>[
          CustomWidget(
            CustomWidgetString: "Custom Widget",
            WidgetKey: "value",
          )
        ],
        onReorder: (a, b){
        },
      ),
    );
  }
}

Using widget available in flutter, don't throw any error. Can you please help?

like image 326
hydroweaver Avatar asked Oct 29 '25 10:10

hydroweaver


1 Answers

You should use ValueKey instead of just Key. Make sure the ValueKey holds the value. It's also critically important that you call super with the key so that it knows what the key is.

class CustomWidget extends StatelessWidget{

  final String customWidgetString;
  final Key key;

  const CustomWidget({this.key, this.customWidgetString}) : super(key: key);

  Widget _widget(){
    return Text(
      customWidgetString,
      key: key,
    );
  }

  @override
  Widget build(BuildContext context){
    return _widget();
  }
}


class AppState extends State<App>{

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: Text("Reorderable List"),
      ),
      body: ReorderableListView(
        scrollDirection: Axis.vertical,
        children: <Widget>[
          CustomWidget(
            key: ValueKey("Custom Widget"),
            customWidgetString: "Custom Widget",
          )
        ],
        onReorder: (a, b){
        },
      ),
    );
  }
}

More reading:

https://medium.com/flutter/keys-what-are-they-good-for-13cb51742e7d

All children of this widget must have a key in Reorderable Listview

And watching:

https://www.youtube.com/watch?v=kn0EOS-ZiIc

like image 169
Benjamin Avatar answered Nov 01 '25 01:11

Benjamin