Map string dynamic to list flutter

The article Parsing Complex JSON in Flutter is very good, but I was looking for something shorter, a quick reference with examples.

If I have a simple JSON string like this:

How do I convert it to a Dart object? Or a Dart object to JSON?

Import the builtin convert library, which includes the jsonDecode[] and jsonEncode[] methods:

In Dart and flutter, this tutorial explains how to convert List to List and vice versa.

A dynamic type is a primitive type that may hold any dynamic value, such as an integer, a string, or a double.

Because a string is a primitive type that stores a collection of characters, automated conversion to/from dynamic is not possible.

You can check on How to convert dynamic to string vice versa or vice versa in Dart and flutter.

How to Convert List of String into List of Dynamic type in Dart

In dart and flutter, this example converts a list of strings to a list of dynamic.

  • List has an array of strings.

  • List. from[] has a named constructor that takes a list of strings. It is a shallow copy of a list.

void main[] { List numbers = ['one', 'two', "four"]; print[numbers.runtimeType]; List dynamicValues = List.from[numbers]; print[dynamicValues.runtimeType]; print[dynamicValues]; }

Output:

JSArray JSArray [one, two, four]

How to parse List of Dynamic into List of String type in Dart

In dart and flutter, this example converts a list of dynamic types to a list of Strings.

map[] is used to iterate over a list of dynamic strings. To convert each element in the map to a String, toString[] is used. Finally, use the toList[] method to return a list.

void main[] { List numbers = ['one', 'two', "four"]; print[numbers.runtimeType]; final List strs = numbers.map[[e] => e.toString[]].toList[]; print[strs.runtimeType]; print[strs]; }

Output:

JSArray JSArray [one, two, four]

Conclusion

Learned how to parse and convert a list of strings into a list of dynamic and vice versa.

In this tutorial, we’re gonna look at several ways to convert Map to List & List to Map in Dart/Flutter using List & Map methods.

Related Posts:
– Dart/Flutter – Sort list of Objects
– Dart/Flutter Constructors tutorial with examples
– Dart/Flutter String Methods & Operators tutorial with examples
– Dart/Flutter Future Tutorial with Examples

– Dart/Flutter List Tutorial with Examples
– Dart/Flutter Map Tutorial with Examples

Overview

Assume that we have a model class like this.

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

What we’ll do is to convert List into Map and vice versa as below.

  • key: Customer’s name
  • value: Customer’s age
// List of Customers [{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }] // Map { name:age } {Jack: 23, Adam: 27, Katherin: 25}

Let’s go to the next sections.

Convert Map to List in Dart/Flutter

Let’s initialize a Dart Map first.

Map map = {'Jack': 23, 'Adam': 27, 'Katherin': 25};

We will convert this Map to List with Customer.name from a key and Customer.age from a value.
Before that, initialize an empty list first.

var list = [];

Using Map forEach[] method

Now we convert our Map to List above using forEach[] method.

map.forEach[[k, v] => list.add[Customer[k, v]]]; print[list];

In the code above, we create a new Customer object from each key-value pair, then add the object to the list.

Output:

[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]

Using Iterable forEach[] method

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

map.entries.forEach[[e] => list.add[Customer[e.key, e.value]]]; print[list];

We apply forEach[] to entries property of the map.
Every entry has a key-value field, we use them to create a new Customer object and add to the list.

Output:

[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]

Using Iterable map[] method

Another way to convert Map to a Dart List is to use Iterable map[] method.

list = map.entries.map[[e] => Customer[e.key, e.value]].toList[]; print[list];

Each entry item of Map’s entries will be mapped to a Customer object with entry.key as customer.name and entry.value as customer.age.
Then we convert the Iterable result to List using toList[] method.

Output:

[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]

Convert List to Map in Dart/Flutter

Before doing our work, we create a List with some items.

List list = []; list.add[Customer['Jack', 23]]; list.add[Customer['Adam', 27]]; list.add[Customer['Katherin', 25]];

Using Map.fromIterable[]

We convert List into Map using fromIterable[] constructor.

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

We pass list as an Iterable for the first param.
Then, for each element of the iterable, the method computes key and value respectively.

Output:

{Jack: 23, Adam: 27, Katherin: 25}

Using Iterable forEach[] method

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

var map2 = {}; list.forEach[[customer] => map2[customer.name] = customer.age]; print[map2];

This method is simple to understand.
We iterate over the list, for each item in the list, we add an entry [key,value] to the Map.

Output:

{Jack: 23, Adam: 27, Katherin: 25}

Conclusion

Today we’ve known how to convert a Map to List in Dart/Flutter using Map.fromIterable[] or Iterable forEach[] method. We also do the opposite thing: convert a List to Map using Map.forEach[], Iterable forEach[] or map[] method.

For more details about these methods, also many interesting thing about Dart List and Map, please visit:
– Dart/Flutter List Tutorial with Examples
– Dart/Flutter Map Tutorial with Examples
– Dart/Flutter – Sort list of Objects

Happy Learning! See you again.

Further Reading

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

– Dart/Flutter Constructors tutorial with examples
– Dart/Flutter String Methods & Operators tutorial with examples
– Dart/Flutter Future Tutorial with Examples

In this post, we will understand the Flutter concepts related to Map with some code example / sample. For greater details, visit Flutter website.

Map maps a String key with the dynamic value. Since the key is always a String and the value can be of any type, it is kept as dynamic to be on the safer side. It is very useful in reading a JSON object as the JSON object represents a set of key-value pairs where key is of type String while value can be of any type including String, List, List or List. Take a look at the following example:

{ "name": "Vitalflux.com", "domain": ["Data Science", "Mobile", "Web"], "noOfArticles": [ {"type": "data science", "count": 50}, {"type": "web", "count": 75} ] }

Above is an example of JSON object comprising of three keys such as name with value of type String, “domain” with value of type List and “noOfArticles” with value of type List [List]

Such JSON objects can easily be read with Map object and displayed on screen appropriately.

There are various ways in which one could work with Map object. They are some of the following:

  • Process it as a Map object
  • Parse it and use it as a Dart object

The following will be required to be done in case the Map is parsed and read as a Dart object.

  • A parse method which will parse the Map
  • A Dart object which is created as a result of parsing

The following code represents the parse method which is used to create a Dart object.

class PortalInfoWidget extends StatelessWidget { Map _portaInfoMap = { "name": "Vitalflux.com", "domains": ["Data Science", "Mobile", "Web"], "noOfArticles": [ {"type": "data science", "count": 50}, {"type": "web", "count": 75} ] }; @override Widget build[BuildContext context] { PortalInfo portalInfo = PortalInfo.fromJson[_portaInfoMap]; return ListView[ children: List.generate[portalInfo.domains.length,[index]{ return Container[ padding: const EdgeInsets.fromLTRB[20.0, 10.0, 10.0, 10.0], child: Text[portalInfo.domains[index].toString[]] ]; }], ]; } }

Note the fromJson factory method called on the PortalInfo [Dart object] which takes the Map object and returns the parsed PortalInfo object. A ListView widget is then created on portalInfo.domains object which is List as represented in Map JSON representation.

Here is the code for PortalInfo object.

class PortalInfo { final String name; final List domains; final List noOfArtcles; PortalInfo[{ this.name, this.domains, this.noOfArtcles }]; factory PortalInfo.fromJson[Map parsedJson]{ return PortalInfo[ name: parsedJson['name'], domains : parsedJson['domains'], noOfArtcles : parsedJson ['noOfArticles'] ]; } }

Running the app will create a view like the following:

Fig 1. Printing List value of Map object

Video liên quan

Chủ Đề