gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:26:33 32 4
gpt4 key购买 nike

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

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)'

这是 Dart 代码:

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 中可用的小部件,不要抛出任何错误。你能帮忙吗?

最佳答案

您应该使用 ValueKey 而不仅仅是 Key。确保 ValueKey 保存值。使用 key 调用 super 也非常重要,这样它就知道 key 是什么。

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

关于flutter - ReorderableListView 不识别自定义小部件中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59444423/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com