Flutter

Flutter learning curve

Using the spread operator in Dart

After mapping an iterable, you may need to turn it into a List; in certain situtations however you may want to add the list into an existing list.

Instead of separately merging the collection, Dart 2.3 introduced the spread operator (...) and the null-aware spread operator (...?), which provide a concise way to insert multiple elements into a collection.

The spread operator is especially useful when mapping Flutter widgets:

    return ListView(
      scrollDirection: Axis.vertical,
      shrinkWrap: true,
      children: [
        Text("Choose a Wiki..."),
        ...this.wikis.map((wiki) {
          return Text(wiki.displayName);
        }).toList()
      ],
    );

After mapping a model (Wiki in this case) to a Widget (Text in this case), we then use toList() to turn it into a compatible type List. If you already have other children in the list, then you cannot simply add the List as an element; but you can spread the list into its elements, thereby merging them into the list in a very consice way.

The null-aware version will ignore the merge if the list is null (be aware that this is not like compactMap in that it checks only if the List is null; it does not check if the elements are null).