Spread操作符和toList用于Flutter中的Map惰性加载



我正在努力更好地理解在Flutter中使用的Dart数据结构。当使用map()将列表转换为小部件时,我看到您在末尾添加了toList(),因为map()使用延迟加载,并且只在需要时迭代。然而,我也看到使用spread operator[...]也可以做到这一点。

在结束这篇SO帖子时,我想知道在这种情况下最好的做法是什么。

我的代码很长,所以我在下面生成了一个类似的可行示例。我需要使用spread运算符在Column内部创建ElevatedButton,但代码可以使用和不使用toList()

我是使用toList(),还是包含它的唯一目的是实现排列运算符已经在做的事情?

void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var answers = [
'Answer 1',
'Answer 2',
'Answer 3',
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('The Question',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
)),
...answers.map(((e) => CustomButton(e)))
// .toList()                                 // should this be included?
],
),
)),
);
}
}
class CustomButton extends StatelessWidget {
final String anAnswer;
CustomButton(this.anAnswer);
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {},
child: Text(anAnswer),
);
}
}

我只需将您的最后一个children元素替换为:

children: [
Text('The Question',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
)),
for (final e in answers) CustomButton(e),
],

其使用循环的列表文本来构建元素。不需要排列运算符,因为您正在将元素直接插入外部列表中。

最新更新