flutterdart

How to use a NESTED "for" loop inside children of a widget?


Having this sample class:

class Mother {
  late String Name;
  late List<String> Children;
}

and this code to get a list of each Mother's name:

...
final Mothers = List<Mother>[];
...
Column(
  children: [
    for (var item in Mothers) Text(item.Name),
  ],
)

I'm looking for an elegant way to have a list of children for each mother as well, in other words I need to process each item.Children object:

Mother1
Child A
Child B
Mother2
Child C
Child D

Thanks.


Solution

  • If you want to display expected result then there is 2 ways using for loop and list view as well

    If you want to use for loop then use 1st for loop then 2nd loop inside Column widget, the outer loop for Mother and inner for child, for more refer below code hope its help to you.

    For Loop

    Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
       // outer loop
        for (var mother in Mothers) ...[
          Text(
            mother.Name,
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          // inner loop
          for (var child in mother.Children)
            Padding(
              padding: const EdgeInsets.all(16.0), // manage padding your way.
              child: Text(child),
            ),
        ],
      ],
    )
    

    Listview

    ListView.builder(
      padding: const EdgeInsets.all(8.0),
      itemCount: Mothers.length,
      itemBuilder: (context, motherIndex) {
        final mother = Mothers[motherIndex];
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              mother.Name,
            ),
            ListView.builder(
              physics: NeverScrollableScrollPhysics(), 
              shrinkWrap: true, 
              itemCount: mother.Children.length,
              itemBuilder: (context, childIndex) {
                final child = mother.Children[childIndex];
                return Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text(child),
                );
              },
            ),
          ],
        );
      },
    )
    

    Result Screen: result