How to combine Lists in Flutter

October 09, 2022 No comments dart flutter combine lists

Introduction

Sometimes, we'll like to combine two or more lists in Flutter. In this tutorial, we'll learn several ways to do it.

How to combine Lists in Flutter

To combine two or more lists in Flutter we can use from() and addAll() method:

var firstList = ['one', 'two'];
var secondList = ['three', 'four'];

var combined = List.from(firstList)..addAll(secondList);
print(combined);

The output:

[one, two, three, four]

Using expand() method to combine lists in Flutter:

var firstList = ['one', 'two'];
var secondList = ['three', 'four'];

var combined = [firstList, secondList].expand((x) => x).toList();
print(combined);

The output:

[one, two, three, four]

Combining lists in Flutter using the operator +:

var firstList = ['one', 'two'];
var secondList = ['three', 'four'];

var combined  = firstList + secondList;
print(combined);

The output:

[one, two, three, four]

Combine lists in Flutter using the spread operator ...:

var firstList = ['one', 'two'];
var secondList = ['three', 'four'];

var combined = [...firstList, ...secondList];
print(combined);

The output:

[one, two, three, four]

The spread operator introduced in Dart 2.3, works similarly to the spread operator available in JavaScript.

Conclusion

In this short tutorial, we showcased several ways to combine lists in Flutter.

{{ message }}

{{ 'Comments are closed.' | trans }}