颤振最神奇的部分是每个小部件都是一个对象。但是,当我试图从Row创建一个对象并向它的子部件添加一个小部件的List时,我在运行时会得到以下错误:
Cannot add to an unmodifiable list我目前正在像这样创建我的Row:
Row rowStar = Row();
rowStar.children.addAll(rowChildren);这样做不对吗?如果是的话,正确的方法是什么?
发布于 2020-03-13 21:36:32
在我的例子中,我可以从先前创建的Row生成一个List<Widget>。
Row calculateListOfStars(ranking) {
final List<Widget> rowList = [];
rowList.addAll([
// make my custom widget
]);
final Row rowStars = Row(
children: rowList,
);
return rowStars;
}发布于 2020-03-24 16:53:36
1.为什么不起作用
如果您只想将一个列表添加到一个Row中,那么您应该创建这个列表,然后用它初始化Row。之后不能添加列表,因为Flutter的小部件通常具有final字段/属性,这些字段/属性在运行时不可修改。
2.颤振方式
但是,动态修改列表所能做的是传递一个在运行时在内部构建列表的函数。这正是ListView的ListView构造函数所做的。
例如,这是用于基于List sContainer和colorCodes动态创建Containers的文档示例。
final List<String> entries = <String>['A', 'B', 'C'];
final List<int> colorCodes = <int>[600, 500, 100];
ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 50,
color: Colors.amber[colorCodes[index]],
child: Center(child: Text('Entry ${entries[index]}')),
);
}
);您可以向.add添加一个按钮,例如字母D和colorCode 400,并在相应的List中添加一个按钮,然后颤振将在屏幕上动态呈现相应的Container。
发布于 2020-03-12 11:32:28
我不知道我做得对不对,但你想做的事没有道理。如果您想重用带有小部件和信息的Row,只需构建一次,并将整个过程保存为小部件。
试着这样做:
Row.
Row(
children: <Widget>[
customWidget1(),
customWidget2(),
customWidget3(),
],
)然后,您的自定义小部件是Row的内容。
希望能帮上忙。
https://stackoverflow.com/questions/60651303
复制相似问题