List object dart

Flutter Dart Convert Map to List & List to Map

Last updated Oct 27, 2021

In this post we are going to learn how to convert Map to List and List to Map in Dart/Flutter.

What is List in Dart?

Dart represents arrays in the form ofListobjects. AListis simply an ordered group of objects

List is classified in two ways

  • Fixed Length List
  • Growable List

What is Map?

The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection

Map can be classified as below

  • Using Map Literals
  • Using a Map constructor

Read dart list tutorial

Let's check

Suppose we have a class called User

class User { String name; int age; User[this.name, this.age]; @override String toString[] { return '{ ${this.name}, ${this.age} }'; } }

Now let's convert List into Map and vice versa

Convert Map to List in Dart/Flutter

Let's initialize Map

Map user_map = {'User1': 23, 'User2': 27, 'User3': 25};

We will convert thisMaptoListwithCustomer.namefrom a key andCustomer.agefrom a value.
Before that, initialize an empty list first

var user_list = [];

Using Map forEach[] method

Now we convert our Map to List above usingforEach[]method

user_map.forEach[[k, v] => user_list.add[User[k, v]]];
print[user_list];

In the code above, we create a newUserobject from each key-value pair, then add the object to the user_list.

Output:

[{ User1, 23 }, { User2, 27 }, { User3, 25 }]

Using Iterable forEach[] method

We can also convert a Dart Map to List using IterableforEach[]method instead.

user_map.entries.forEach[[e] => user_list.add[User[e.key, e.value]]];
print[user_list];

Output:

[{ User1, 23 }, { User2, 27 }, { User3, 25 }]

Using Iterable map[] method

Another way to convert Map to a Dart List is to use Iterablemap[]method

user_list= map.entries.map[[e] => User[e.key, e.value]].toList[]; print[user_list];

Each entry item of Mapsentrieswill be mapped to a Userobject withentry.keyasuser.nameandentry.valueasuser.age.


Then we convert theIterableresult toListusingtoList[]method

Output:

[{ User1, 23 }, { User2, 27 }, { User3, 25 }]

Convert List to Map in Dart/Flutter

Now Let's create a List with User Info

List list = []; list.add[User['User1', 23]]; list.add[User['User2', 27]]; list.add[User['User3', 25]];

Using Map.fromIterable[]

We convertListintoMapusingfromIterable[]constructor

var map1 = Map.fromIterable[list, key: [e] => e.name, value: [e] => e.age]; print[map1];

Using Iterable forEach[] method

We can convert Dart List to Map in another way:forEach[]method

var map = {}; list.forEach[[user] => map[user.name] = user.age]; print[map];

Compare list and maps using DeepCollectionEquality collection class

Conclusion: In this Dart tutorial we covered how to convert list to map and map to list in different ways

Read More

  • Dart List class
  • Dart Map class
  • Dart Iterable class

Article Contributed By :
RRTutors

19261 Views

Video liên quan

Chủ Đề