[英]How can I use for loop in flutter?
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
Column(
children: <Widget>[
NewsBlock(
size: size,
dataList: dataList,
imgNum: 1,
titleNum: 11,
urlNum: 21,
),
NewsBlock(
size: size,
dataList: dataList,
imgNum: 2,
titleNum: 12,
urlNum: 22,
),
NewsBlock(
size: size,
dataList: dataList,
imgNum: 3,
titleNum: 13,
),
NewsBlock(
size: size,
dataList: dataList,
imgNum: 4,
titleNum: 14,
),
],
)
],
),
],
)),
);
I want to make that long code to short with for loop.我想用 for 循环将长代码缩短。 But I don't know how to use for loop in flutter.. I think I can reduce the length of code by putting i in imgNum, titleNum, and urlNum and increasing i.但是我不知道如何在flutter中使用for循环..我认为我可以通过将i放入imgNum,titleNum和urlNum并增加i来减少代码长度。 How can I do that?我怎样才能做到这一点? (btw there are 10 news blocks and I didn't write urlNum for all news blocks yet because typing all them made me feel like a fool) (顺便说一句,有 10 个新闻块,我还没有为所有新闻块写 urlNum,因为输入所有新闻块让我觉得自己像个傻瓜)
You can use for loop like this:您可以像这样使用 for 循环:
final maxSize = ???;
final imgStartIndex = 1;
final titleStartIndex = 11;
final urlStartIndex = 21;
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
Column(
children: <Widget>[
for (int i = 0; i < maxSize; i++)
NewsBlock(
size: size,
dataList: dataList,
imgNum: imgStartIndex + i,
titleNum: titleStartIndex + i,
urlNum: urlStartIndex + i,
),
],
)
],
),
],
)),
);
I do not know the structure of your data, so you should guess yourself how to calculate maxSize ;我不知道你的数据结构,所以你应该自己猜怎么计算maxSize ;
To your question, you can do like this对于你的问题,你可以这样做
children: [
for (var i = 0; i < List.length; i++)
NewsBlock()
],
Other way to do is to use map in the list data其他方法是在列表数据中使用地图
children: newsData.map((item)=>NewsBlock(
size: item.size,
dataList: item.datalist,
imgNum: item.imgNum,
titleNum: item.titleNum,
)).toList()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.