簡體   English   中英

如何在小部件的子項中使用“for”循環?

[英]How to use a "for" loop inside children of a widget?

我真的很困惑,FOR 循環應該放在哪里,這樣我就不會在 flutter 中出錯? 正如您在圖片上看到的,它帶有紅色下划線並表示。

在此處輸入圖像描述

兩種選擇:

final children = <Widget>[];
for (var i = 0; i < 10; i++) {
  children.add(new ListTile());
}
return new ListView(
  children: children,
);

或者

return new ListView(
  children: new List.generate(10, (index) => new ListTile()),
);

對於ListViewColumn等小部件,有多種方法可以在子級中使用for循環。

  • 使用for循環

    ListView( children: [ for (var i = 0; i < 10; i++) Text('Item $i'), ], )
  • 使用for-each循環

    ListView( children: [ for (var item in items) Text(item), ], )
  • ...[]for循環結合

    ListView( children: [ ...[ Text('Item 0'), Text('Item 1'), ], for (var item in items) Text(item), // Rest of the items ], )

我們也可以使用擴展運算符來添加多個使用 for 循環的小部件

Column(
 children: [
 Container() /// we can add some other widgets
 for (var i = 0; i < 3; i++) ...[
    CardListItem(),
    Divider(),
  ],
]

使用json響應在flutter中進行簡單的for循環

  Widget build(BuildContext context) {
var list = [{'id':"123123","date":"20/08/2016"},{'id':"123124","date":"26/08/2016"},{'id':"123125","date":"26/08/2016"}]; 
   return Scaffold(
  appBar: AppBar(
    title: Text(widget.title),
  ),
  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text('Recent Claims'),
        Table(
          border: TableBorder.all(color: Colors.black),
          columnWidths: {
            0: FixedColumnWidth(100.0),
            1: FixedColumnWidth(100.0)
          },
          children:[
            for(var item in list )  TableRow(children: [
              Text(item['id']),
              Text(item['date']),
          ])]
           ),
      }

如果您要迭代的對象是一個 Iterable(例如 List 或 Set),並且您不需要知道當前的迭代計數器,則可以使用 for-in 形式的迭代

以下是您在Dart 2.3 中的做法:

Row(
 children: <Widget>[
  for (var city in myCity) Text("New ${city.name}")
  ],
)

您還可以使用.map()運算符並執行以下操作

Widget getTextWidgets(List<String> strings)
  {
    return new Row(children: strings.map((item) => new Text(item)).toList());
  }

如果您沒有List

ListView(
  scrollDirection: Axis.horizontal,
  children: List.generate(10, (index) => …),
),

別的:

ListView(
  scrollDirection: Axis.horizontal,
  children: list.map((e) => …).toList(),
),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM