【问题标题】:ReorderableListView does not identify keys in Custom WidgetReorderableListView 无法识别自定义小部件中的键
【发布时间】:2019-12-22 13:01:33
【问题描述】:

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

此小部件的所有子级都必须有一个键。 'package:flutter/src/material/reorderable_list.dart': 失败 断言:第 71 行 pos 10: 'children.every((Widget w) => w.key != 空)'

这是飞镖代码:

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 dart


    【解决方案1】:

    您应该使用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

    【讨论】:

    • 非常感谢!它有效,我将通过链接查看我的错误:)
    • 看起来超级与众不同! + 价值键!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2019-08-27
    相关资源
    最近更新 更多