ReorderableListView无法识别“自定义小部件”中的键

时间:2019-12-22 13:01:33

标签: flutter dart

我有一个ReorderableListView应该填充自定义小部件,但是即使在自定义无状态小部件类和构造函数中传递了键,我也会收到以下错误:

  

此小部件的所有子代必须具有密钥。   'package:flutter / src / material / reorderable_list.dart':失败   断言:第71行pos 10:'children.every((Widget w)=> w.key!=   null)'

这是飞镖代码:

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){
        },
      ),
    );
  }
}

使用在flutter中可用的小部件,不要抛出任何错误。你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

您应该使用ValueKey而不是Key。确保ValueKey保留该值。用密钥调用super也很重要,这样它才能知道密钥是什么。

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){
        },
      ),
    );
  }
}

更多阅读内容:

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

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

正在观看:

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