Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating widgets inside nested for loop

Tags:

flutter

dart

I am not able to access the outer for loop counter in inner for loop

Any idea on how to do this ?

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
like image 743
user3048099 Avatar asked Jan 27 '23 02:01

user3048099


1 Answers

You don't have a nested loop here. Please see the comments I added below:

  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())
      ],
    )
  ],

Here's how you can create categories in a nested loop:

  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())
        ],
      )
    ]
  ],

Note that to add two elements in each loop iteration we had to put the two into a list and unwrap it with the ... spread operator.

like image 64
Gazihan Alankus Avatar answered Feb 05 '23 14:02

Gazihan Alankus