在嵌套的 for 循环中创建小部件

use*_*099 2 dart flutter

我无法访问内部 for 循环中的外部 for 循环计数器

关于如何做到这一点的任何想法?

class buildsubcategories extends StatelessWidget {
  List<cate.Categories> scat;

  buildsubcategories(this.scat);
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        for (int i = 0; i < scat.length; i++) Text(scat[i].categoryname),
        Column(
          children: <Widget>[
            for (int j = 0; j < scat.length; j++)
              Text(scat[i].subcategory[j]['subcategoryname'].toString())
          ],
        )
      ],
    );
  }
```}


Expected Result : Able to access the variable i in the inner for loop
Run Code Online (Sandbox Code Playgroud)

Gaz*_*kus 6

这里没有嵌套循环。请参阅我在下面添加的评论:

  children: <Widget>[
    // this creates scat.length many Text elements here
    for (int i = 0; i < scat.length; i++) Text(scat[i].categoryname),
    // there is only one column that comes after the scat.length many Text elements 
    Column(
      children: <Widget>[
        // this creates scat.length many elements inside the Column
        for (int j = 0; j < scat.length; j++)
          Text(scat[i].subcategory[j]['subcategoryname'].toString())
      ],
    )
  ],
Run Code Online (Sandbox Code Playgroud)

以下是在嵌套循环中创建类别的方法:

  children: <Widget>[
    // note the ... spread operator that enables us to add two elements 
    for (int i = 0; i < scat.length; i++) ...[ 
      Text(scat[i].categoryname),
      Column(
        children: <Widget>[
          // this creates scat.length many elements inside the Column
          for (int j = 0; j < scat.length; j++)
            Text(scat[i].subcategory[j]['subcategoryname'].toString())
        ],
      )
    ]
  ],
Run Code Online (Sandbox Code Playgroud)

请注意,要在每次循环迭代中添加两个元素,我们必须将这两个元素放入一个列表中,并使用...展开运算符展开它。