Flutter/Dart : For Loop Inside a Widget

Can someone please explain how the for loop in this snippit works with the spread operator? It seems the spread should be operating on a single item collection, the Column. But I had to use the spread operator when I added the Text element in the Column’s children. How does the flow work between the for loop, spread, Column, and it’s children when building this widget? Thanks! Oh, and what’s the reason why Flutter doesn’t allow curly brackets for the body of a for loop inside the logic for building a widget? I assume there’s a syntactical reason.

    return ListView(
      children: [
        Padding(
          padding: const EdgeInsets.all(20),
          child: Text('You have ${appState.favorites.length} favorites.'),
        ),

        for (var pair in appState.favorites)... [
          Column(
            children: [
              Text(pair.asLowerCase),
              ListTile(
                leading: Icon(Icons.favorite),
                title: Text(pair.asLowerCase),
              ),
            ]
          )
        ],
      ],
    );

I tried to logically compile the code in my head.

  • Spread Operator (…) and Null-aware Spread Operator (…?) are used for inserting multiple elements in a collection like Lists, Maps, etc. Here in this case the loop works and create multiple elements and directly adds it inside the listview as its children’s element.

    – 

  • 2

    Read dart.dev/language/collections#control-flow-operators and medium.com/dartlang/…. In your case, ...[Column(arguments)] could be just Column(arguments); spreading a list of one element is pointless. Collection-for (and collection-if) don’t use curly braces because their body must be an element, not arbitrary statements.

    – 

  • Ahh… so I don’t really need the spread operator! Somewhere along the way, it seemed like I needed it to make it work after I added the Text element. Thanks for looking at this post @jamesdlin.

    – 

  List list1 = [];
  List list2 = [3, 4, 5];

  spread() {
    list1 = [1, for(var val in list2) ...[val]];
    //[1, ...[3]]
    //[1, ...[4]]
    //[1, ...[5]]
  }

this fist intem in this children on your example is Pading() and on my example is 1

using spread operator you can add full of the list2 with list1. on you example index 2 created depends on length of appState.favorites. on my example its [3, 4, 5]

just compare the your code with my example i think got proper explanation

Leave a Comment