How to Combine Two Lists In Dart ??

3 min read
How to Combine Two Lists In Dart
How to Combine Two Lists In Dart

When a user is receiving a data from two different source in a list format user need to concatenate two lists in a dart to create a brand new list object. So in today’s article, we will go through How to Combine Two Lists In Dart.

Are you ready to learn Flutter Development with Flutter Agency?? Then let’s get started…

How to Combine Two Lists In Dart??

Consider a case where is having a two list like a below:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

and the user wants to get a combined output like a below:

[1, 2, 3, 4, 5, 6]

In order to combine the two lists, you can give it a try at the below code snippet.

var newList = new List.from(list1)..addAll(list2);

If you have several lists you can use:

var newList = [list1, list2, list3].expand((x) => x).toList()

As of Dart 2, you can now use +

var newList = list1 + list2 + list3;

As of Dart 2.3, you can use the spread operator:

var newList = [...list1, ...list2, ...list3];

Darts operator overloading:

class MyList<T>{
  List<T> _internal = new List<T>();
  operator +(other) => new List<T>.from(_internal)..addAll(other);
  noSuchMethod(inv){
    //pass all calls to _internal
  }
}

Then use this:

var newMyList = myList1 + myList2;

Maybe more consistent as sown below

var list = []..addAll(list1)..addAll(list2);

Dart now supports the concatenation of lists using the + operator.

You can refer to the below Example:

List<int> result = [0, 1, 2] + [3, 4, 5];

If you want to merge two lists and remove duplicates could do:

var newList = [...list1, ...list2].toSet().toList();

Conclusion:

Thanks for being with us on a flutter journey!!! Keep Learning!! Keep Fluttering!!

Don’t forget to drop your feedback in the comments right below!! That way we can know how can we improve 馃檪

So in this article, we have been through how to combine two lists in Dart.

Do let us know if you need any assistance with flutter development?? We would love to assist you.

FlutterAgency.com聽is our portal Platform dedicated to Flutter Technology and聽Flutter Developers. The portal is full of cool resources from Flutter like聽Flutter Widget聽Guide,聽Flutter Projects,聽Code libs聽and etc.

FlutterAgency.com is one of the most popular online portals dedicated to聽Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of聽Flutter.

2 comments

Leave a Reply