我对项目列表的状态有些麻烦。我想保存每个项目的状态以及整个列表的某些状态。对我的实施有什么想法或指导吗?标有“ ###”的错误。谢谢。另外,如何格式化一组粘贴的代码行? ctrl-K只是将它们吹灭了,添加pre / code标记仍然会引起红色投诉。我只是在每行中添加了4个空格以使其正常工作。
class TruffleListScreenList extends StatefulWidget {
@override
TruffleListScreenListState createState() {
return TruffleListScreenListState();
}
}
class TruffleListScreenListState extends State<TruffleListScreenList> {
List<TruffleItemState> truffleItems = [
TruffleItemState("chocolate", "images/IMG_1252.JPG"),
TruffleItemState("mint", "images/IMG_1253.JPG"),
TruffleItemState("tooti-frutti", "images/IMG_1254.JPG"),
TruffleItemState("peanut butter", "images/IMG_1255.JPG"),
];
@override
Widget build(BuildContext context) {
return ListView(
children: truffleItems, ### The argument type 'List TruffleItemState' can't be assigned to the parameter type 'List Widget'
);
}
}
class TruffleItem extends StatefulWidget {
@override
TruffleItemState createState() {
return TruffleItemState(); ### 2 required argument(s) expected, but 0 found.
}
}
class TruffleItemState extends State<TruffleItem> {
String name;
String imageFile;
int qty;
bool add;
TruffleItemState(this.name, this.imageFile);
@override
Widget build(BuildContext context) { // build a row of stuff as a list item
return Row(
);
}
}
答案 0 :(得分:1)
小部件的结构看起来不错:一个用于列表,一个用于每个列表项。
下一步是为每个TruffleItem
创建一个小部件列表,并在子级中将其用于ListView。为此,您将需要在List类上使用map函数。另外,根据我的经验,您必须两次传递参数。一次用于StatefulWidget,然后复制到State。
您的代码应如下所示:
class TruffleListScreenList extends StatefulWidget {
@override
TruffleListScreenListState createState() {
return TruffleListScreenListState();
}
}
class TruffleListScreenListState extends State<TruffleListScreenList> {
List<TruffleItemState> truffleItems = [
TruffleItemState("chocolate", "images/IMG_1252.JPG"),
TruffleItemState("mint", "images/IMG_1253.JPG"),
TruffleItemState("tooti-frutti", "images/IMG_1254.JPG"),
TruffleItemState("peanut butter", "images/IMG_1255.JPG"),
];
@override
Widget build(BuildContext context) {
return ListView(
// Map each item to a widget, then turn into a list.
children: truffleItems.map((item) => TruffleItem(item.name, item.imageFile)).toList(),
);
}
}
class TruffleItem extends StatefulWidget {
final String name;
final String imageFile;
TruffleItem(this.name, this.imageFile);
@override
TruffleItemState createState() {
return TruffleItemState();
}
}
class TruffleItemState extends State<TruffleItem> {
int qty;
bool add;
TruffleItemState();
@override
Widget build(BuildContext context) { // build a row of stuff as a list item
return Row(
// Use the variables like widget.name or widget.imageFile
);
}
}
如理查德·希普(Richard Heap)的评论所述:
“不要将名称和imageFile传递给TruffleItemState。相反, 您可以从那里访问它们作为widget.name和widget.imageFile 分别。”