flutter - 在 Flutter 中循环遍历列表数据
问题描述
在 Flutter 中循环嵌套列表的最佳方法是什么?我正在使用以下代码,但我认为这不是最佳做法,因为我在同一个父小部件内循环遍历列表两次:
class DetailItem extends StatelessWidget {
DetailItem({
required this.index,
required this.data,
required this.lastItem,
});
final List data;
final int index;
final bool lastItem;
String? paragraph;
int id = 0;
@override
Widget build(BuildContext context) {
final row = SafeArea(
top: false,
bottom: false,
minimum: const EdgeInsets.only(
left: 10,
top: 0,
bottom: 8,
right: 8,
),
child: Row(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.only(
left: 10,
top: 8,
bottom: 8,
right: 8,
),
child: Column(
children: <Widget>[
for (var s in data) //loop
Column(
children: <Widget>[
SizedBox(height: 30),
Align(
alignment: Alignment.centerLeft,
child: Text(s.name.toUpperCase(), style: Styles.itemRowItemLanguage, textAlign: TextAlign.start),
),
SizedBox(height: 5),
Align(
alignment: Alignment.centerLeft,
child: Text(s.paragraph, style: Styles.itemRowItemName),
),
],
)
],
),
),
),
Column (
children: <Widget>[
new CupertinoButton(
padding: EdgeInsets.zero,
minSize: 0,
child: Icon(CupertinoIcons.share, semanticLabel: 'Share'),
onPressed: () {
Share.share(this.paragraph!);
},
),
new CupertinoButton(
padding: EdgeInsets.zero,
child: Icon(CupertinoIcons.bookmark, semanticLabel: 'Bookmark'),
onPressed: () {
final model = Provider.of<BookmarkModel>(context, listen: false);
for (var s in data) // looping here again
model.toggleBookmarkStatus(s.id);
},
),
],
),
],
),
);
if (lastItem) {
return row;
}
return Column(
children: <Widget>[
row,
Padding(
padding: const EdgeInsets.only(
left: 0,
right: 0,
),
child: Container(
height: 1,
color: Styles.itemRowDivider,
),
),
],
);
}
}
当我在嵌套列小部件外但在父小部件内运行循环时,它显示小部件中的undefined name 's'
错误CupertinoButton
:
final row = SafeArea(
top: false,
bottom: false,
minimum: const EdgeInsets.only(
left: 10,
top: 0,
bottom: 8,
right: 8,
),
child: Row(
children: <Widget>[
for (var s in data) //running the loop inside parent widget but outside the child widget
解决方案
您的代码已经很好,无法合并这些循环。第一个循环在您创建后立即运行row
(即使用户没有按下任何按钮),而第二个循环只会在用户按下CupertinoButton
.
推荐阅读
- cluster-analysis - How aggregate() function uses a cutree() values?
- vue.js - 在插槽上执行 js
- c++ - 调用删除后指针无效
- pandas - 使用熊猫计算列中的项目
- r - 使用多个 ID 列和值列使用 pivot_longer() 简化gather()
- javascript - 播放暂停按钮在选项卡到选项卡上不起作用
- python - subwin 窗口是否应该比内容大一号
- java - 如何使用 Jersey 客户端通过 https 访问有效的 Oracle 页面?
- html - 这个图像比较滑块如何响应?
- c# - 如何将字符串数组转换为int数组