ReorderableListView 不识别自定义小部件中的键

hyd*_*ver 3 dart flutter

我有一个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){
        },
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*min 6

您应该使用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){
        },
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

更多阅读:

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

此小部件的所有子项都必须在 Reorderable Listview 中有一个键

并观看:

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