Add list to list 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 todays article, we will go through How to Combine Two Lists In Dart.

Are you ready to learn Flutter Development with Flutter Agency?? Then lets 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{ List _internal = new List[]; operator +[other] => new List.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 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!!

Dont 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.comis our portal Platform dedicated to Flutter Technology andFlutter Developers. The portal is full of cool resources from Flutter likeFlutter WidgetGuide,Flutter Projects,Code libsand etc.

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

Share this:

  • Click to share on Twitter [Opens in new window]
  • Click to share on Facebook [Opens in new window]
  • Click to share on LinkedIn [Opens in new window]
  • Click to share on Reddit [Opens in new window]
  • Click to share on Tumblr [Opens in new window]
  • Click to share on WhatsApp [Opens in new window]
Advertisement

Video liên quan

Chủ Đề