List key value flutter

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 of List objects. A List is 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 this Map to List with Customer.name from a key and Customer.age from a value.
Before that, initialize an empty list first

Using Map forEach[] method

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

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

In the code above, we create a new User object 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 Iterable forEach[] 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 Iterable map[] method

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

Each entry item of Map’s entries will be mapped to a User object with entry.key as user.name and entry.value as user.age.


Then we convert the Iterable result to List using toList[] 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 convert List into Map using fromIterable[] 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

Contents

Contents

If you have a relatively small collection of key-values to save, you can use the shared_preferences plugin.

Normally, you would have to write native platform integrations for storing data on both iOS and Android. Fortunately, the shared_preferences plugin can be used to persist key-value data on disk. The shared preferences plugin wraps NSUserDefaults on iOS and SharedPreferences on Android, providing a persistent store for simple data.

This recipe uses the following steps:

  1. Add the dependency.
  2. Save data.
  3. Read data.
  4. Remove data.

1. Add the dependency

Before starting, add the shared_preferences plugin to the pubspec.yaml file:

dependencies: flutter: sdk: flutter shared_preferences: ""

2. Save data

To persist data, use the setter methods provided by the SharedPreferences class. Setter methods are available for various primitive types, such as setInt, setBool, and setString.

Setter methods do two things: First, synchronously update the key-value pair in-memory. Then, persist the data to disk.

3. Read data

To read data, use the appropriate getter method provided by the SharedPreferences class. For each setter there is a corresponding getter. For example, you can use the getInt, getBool, and getString methods.

To delete data, use the remove[] method.

Supported types

Although key-value storage is easy and convenient to use, it has limitations:

  • Only primitive types can be used: int, double, bool, string, and stringList.
  • It’s not designed to store a lot of data.

For more information about shared preferences on Android, see the shared preferences documentation on the Android developers website.

Testing support

It’s a good idea to test code that persists data using shared_preferences. You can do this by mocking out the MethodChannel used by the shared_preferences library.

Populate SharedPreferences with initial values in your tests by running the following code in a setupAll[] method in your test files:

Complete example

In this tutorial, we’ll show you many methods and functions to work with a Map in Dart [also in Flutter]. You will know:

  • Introduction to Dart Map, HashMap, LinkedHashMap, SplayTreeMap
  • How to create, initialize, add, get value, update, remove entriess in a Map
  • Ways to iterate, search, filter, transform a Map in Dart/Flutter
  • Way to sort a Map in Dart/Flutter

Related Posts:
– Dart/Flutter – Convert Object to JSON string
– Dart/Flutter – Convert/Parse JSON string, array into Object, List
– Dart/Flutter – Convert Map to List & List to Map

– 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

Key points to note about Dart Map

A Dart Map is a collection of key-value pairs. It maps each key to exactly one value. We can iterate over a Map.

There are three types of map, depending in the order of iteration:

  • HashMap is unordered. The key-value pair coming later could be ordered first.
  • LinkedHashMap has predictable iteration order by the insertion order. The key-value pair coming later will be ordered later.
  • SplayTreeMap iterates the keys in sorted order. It is a self-balancing binary tree, frequently accessed elements will be moved more closely to the root of the tree.

By default, creating an instance using Map constructor [Map[], Map.from[], Map.of[]] will return a LinkedHashMap.

So in the next sections, wherever we use Map, you can think about LinkedHashMap, and you can also replace Map with LinkedHashMap.

Create a new Map in Dart/Flutter

Using new keyword, we can create a new Map.
Don’t forget to import dart:collection library before using these syntax containing HashMap, LinkedHashMap, SplayTreeMap, also other code in the rest of this tutorial.

import 'dart:collection'; main[] { HashMap hashMap = new HashMap[]; LinkedHashMap linkedHashMap = new LinkedHashMap[]; SplayTreeMap treeMap = new SplayTreeMap[]; }

With recent Dart version, we don’t need to use new keyword anymore.
For example, HashMap map = HashMap[] is accepted.

We can create a new LinkedHashMap using Map constructor like this.

Map map = Map[]; if [map is LinkedHashMap] { print["This is a LinkedHashMap."]; } // Result: This is a LinkedHashMap.

In the code above, we specify the type of key-value pairs: .
You can also declare a Map, LinkedHashMap, SplayTreeMap without setting the type for their keys and values. What does it mean? It will not constrain us to add a pair into the Map.

These Maps now accept other types: , …

Map map = Map[]; HashMap map1 = HashMap[]; LinkedHashMap map2 = LinkedHashMap[]; SplayTreeMap map3 = SplayTreeMap[];

Initialize a Map with values in Dart/Flutter

The examples show you how to:

  • initialize Map in simple way using {} [curly braces].
  • create a Map with all key/value pairs of other Map using from[], of[] constructor.
  • create a new Map from the given keys and values using fromIterables[].
  • create Map in which keys and values are computed using fromIterable[]
  • create a ‘const’ Map using unmodifiable[] constructor.
Map map1 = {'zero': 0, 'one': 1, 'two': 2}; print[map1]; // not specify key-value type Map map2 = {'zero': 0, 'I': 'one', 10: 'X'}; print[map2]; var map3 = {'zero': 0, 'I': 'one', 10: 'X'}; print[map3];

Remember that when we use Map or var, the type will always be LinkedHashMap.
Output:

{zero: 0, one: 1, two: 2} {zero: 0, I: one, 10: X} {zero: 0, I: one, 10: X} Map map1 = {'zero': 0, 'one': 1, 'two': 2}; Map map2 = Map.from[map1]; print[map2]; Map map3 = Map.of[map1]; print[map3];

Output:

{zero: 0, one: 1, two: 2} {zero: 0, one: 1, two: 2} List letters = ['I', 'V', 'X']; List numbers = [1, 5, 10]; Map map = Map.fromIterables[letters, numbers]; print[map];

Output:

{I: 1, V: 5, X: 10} List numbers = [1, 2, 3]; Map map = Map.fromIterable[ numbers, key: [k] => 'double ' + k.toString[], value: [v] => v * 2]; print[map];

Output:

{double 1: 2, double 2: 4, double 3: 6} Map map = Map.unmodifiable[{1: 'one', 2: 'two'}]; print[map]; // {1: one, 2: two} map[3] = 'three';

If you try to modify/add object to the unmodifiable Map, it will throw an error.

Unhandled exception: Unsupported operation: Cannot modify unmodifiable map

Difference between Map.from[] and Map.of

Look at the example below, we try to create two Map with wrong type:

Map map = {1: 'one', 2: 'two'}; Map map1 = Map.from[map]; // runtime error Map map2 = Map.of[map]; // compilation error

You can see that:
– Map.from[map] doesn’t cause any compilation error. When we run the statement, the error occurs:

Unhandled exception: type 'int' is not a subtype of type 'String'

This is because of its prototype:

Map Map.from[Map other]

When we pass a Map map to the function, it converts the key-value pair type into Map.

– Map.of[map] doesn’t do that thing, it keep the key-value pair type, so the compiler realizes the error before running the program.

Map Map.of[Map other]

Dart/Flutter Map collection if and collection for

With the collection if and collection for, we can dynamically create maps using conditionals [if] and repetition [for].

var mobile = true; var myMap = {1: 'kotlin', 2: 'dart', if [mobile] 3: 'flutter'}; // {1: kotlin, 2: dart, 3: flutter} var squareMap = { for [var i = 1; i 5] i++: s}; // {0: kotlin, 1: flutter}

Add item to a Map in Dart/Flutter

There are 2 way to add an item [key-value pair] to a Map:

  • using square brackets []
  • calling putIfAbsent[] method
Map map = {1: 'one', 2: 'two'}; map[3] = 'three'; print[map]; var threeValue = map.putIfAbsent[3, [] => 'THREE']; print[map]; print[threeValue]; // the value associated to key, if there is one map.putIfAbsent[4, [] => 'four']; print[map];

Output:

{1: one, 2: two, 3: three} {1: one, 2: two, 3: three} three {1: one, 2: two, 3: three, 4: four}

You can add all key/value pairs of another Map to current Map using addAll[] method.

Map map = {1: 'one', 2: 'two'}; map.addAll[{3: 'three', 4: 'four', 5: 'five'}]; print[map];

Output:

{1: one, 2: two, 3: three, 4: four, 5: five}

Map update value by key in Dart/Flutter

The examples show you how to update a Map value using:

  • square brackets []
  • update[] method
  • update[] method with ifAbsent to add a new object/entry if the input key is absent
Map map = {1: 'one', 2: 'two'}; map[1] = 'ONE'; print[map]; map.update[2, [v] { print['old value before update: ' + v]; return 'TWO'; }]; print[map]; map.update[3, [v] => 'THREE', ifAbsent: [] => 'addedThree']; print[map];

Output:

{1: ONE, 2: two} old value before update: two {1: ONE, 2: TWO} {1: ONE, 2: TWO, 3: addedThree}

Access items from Map in Dart/Flutter

The examples show you way to:

  • find the number of key/value pairs using .length getter.
  • check if a Map is empty or not using .isEmpty or .isNotEmpty.
  • get all keys or values with keys & values property.
  • get value of specified key in a Map or operator [].
Map map = {1: 'one', 2: 'two'}; print[map.length]; // 2 print[map.isEmpty]; // false print[map.isNotEmpty]; // true print[map.keys]; // [1, 2] print[map.values]; // [one, two] print[map[2]]; // two print[map[3]]; // null

Dart/Flutter check existence of key/value in Map

We can check existence of:

  • a key using containsKey[] method.
  • a value using containsValue[] method.
Map map = {1: 'one', 2: 'two'}; print[map.containsKey[1]]; // true print[map.containsKey[3]]; // false print[map.containsValue['two']]; // true print[map.containsKey['three']]; // false

The examples show you how to:

  • remove key-value pair by key using remove[] method.
  • remove all entries with condition using removeWhere[] method.
  • remove all entries from a Map using clear[] method.
Map map = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}; map.remove[2]; print[map]; map.removeWhere[[k, v] => v.startsWith['f']]; print[map]; map.clear[]; print[map];

Output:

{1: one, 3: three, 4: four, 5: five} {1: one, 3: three} {}

Combine/merge multiple Maps in Dart/Flutter

The examples show how to combine Maps using:

  • addAll[] method
  • from[] and addAll[] method
  • spread operator ... or null-aware spread operator ...? [from Dart 2.3]
Map map1 = {1: 'one', 2: 'two'}; Map map2 = {3: 'three'}; Map map3 = {4: 'four', 5: 'five'}; // addAll[] method var combinedMap1 = {}..addAll[map1]..addAll[map2]..addAll[map3]; print[combinedMap1]; // from[] and addAll[] method var combinedMap2 = Map.from[map1]..addAll[map2]..addAll[map3]; print[combinedMap2]; // spread operator var combinedMap3 = {...map1, ...map2, ...map3}; print[combinedMap3];

Output:

{1: one, 2: two, 3: three, 4: four, 5: five}

What if there is one of 3 Maps is null:

Map map1 = {1: 'one', 2: 'two'}; Map map2 = null; Map map3 = {4: 'four', 5: 'five'};

If we combine these Maps using the methods above, the program will throw Exception:

NoSuchMethodError: The getter 'keys' was called on null.

To deal with it, we use null-aware spread operator ...?. The operator check null Map automatically with only one more ? symbol:

var combinedMap = {...?map1, ...?map2, ...?map3}; print[combinedMap];

Output:

{1: one, 2: two, 4: four, 5: five}

Iterate over Map in Dart/Flutter

The examples show you how to iterate over a Dart Map using:

  • forEach[] method.
  • entries property and forEach[] method.
Map map = {1: 'one', 2: 'two', 3: 'three'}; map.forEach[[k, v] { print['{ key: $k, value: $v }']; }]; map.entries.forEach[[e] { print['{ key: ${e.key}, value: ${e.value} }']; }];

Output:

{ key: 1, value: one } { key: 2, value: two } { key: 3, value: three }

We can iterate over keys or values using Map property and forEach[] method.

map.keys.forEach[[k] => print[k]]; map.values.forEach[[v] => print[v]];

Output:

1 2 3 one two three

Dart/Flutter Map get key by value

Dart Map supports getting value by key, how about the opposite?
We can get key by a specified value using keys property and List firstWhere[] method.

Map map = {1: 'one', 2: 'two', 3: 'three'}; var key = map.keys.firstWhere[[k] => map[k] == 'two', orElse: [] => null]; print[key]; // 2

Sort a Map in Dart/Flutter

The example shows you how to sort a Map by values using Map fromEntries[] method and List sort[] method.

Map map = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}; var sortedMap = Map.fromEntries[ map.entries.toList[] ..sort[[e1, e2] => e1.value.compareTo[e2.value]]]; print[sortedMap];

Output:

{5: five, 4: four, 1: one, 3: three, 2: two}

For more details about sorting with List, please visit:
Sorting a List in Dart/Flutter

Map.map[] method to transform a Map in Dart/Flutter

We can use map[] method to get a new Map with all entries are transformed.

For example, the code below change keys and uppercase values of all entries.

Map map = {1: 'one', 2: 'two', 3: 'three'}; var transformedMap = map.map[[k, v] { return MapEntry['[$k]', v.toUpperCase[]]; }]; print[transformedMap];

Output:

{[1]: ONE, [2]: TWO, [3]: THREE}

Conclusion

In this Dart/Flutter tutorial, we’ve learned some important points of Dart Map, HashMap, LinkedHashMap, how to create, initialize a Map, how to add, update and remove items from a Map, how to combine Maps, how to iterate over a Map, sort, transform a Map.

Happy learning! See you again!

Further Reading

  • Dart Map class
  • Effective Dart: Usage – Collection

– Dart/Flutter – Convert Object to JSON string
– Dart/Flutter – Convert/Parse JSON string, array into Object, List
– Dart/Flutter – Convert Map to List & List to Map

– 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

Video liên quan

Chủ Đề