DEV Community

Cover image for Dart/Flutter Map Tutorial – Create/Add/Delete/Iterate/Sorting
JavaSampleApproach
JavaSampleApproach

Posted on

Dart/Flutter Map Tutorial – Create/Add/Delete/Iterate/Sorting

Dart Map Flutter Tutorial.

In the tutorial, I will introduce how to work wiht Dart Map by example coding. What will we do?

https://loizenai.com/dart-map-tutorial/
https://grokonez.com/dart-map-tutorial/

  • How to Initial Dart Map by literal or constructor?
  • Add new entry with Dart Map
  • Iterate through Dart Map
  • Update a Dart Map
  • Delete with Dart Map
  • Convert Dart Map to List
  • Sorting a Dart Map

A collection of key/value pairs, from which you retrieve a value using its associated key.
Keys and values in a map may be of any type. A Map is a dynamic collection. Maps, and their keys and values, can be iterated.

Implementers

  • HashMap, HttpSession, LinkedHashMap, MapMixin, MapView

Dart Map Literals

To declare a map using map literals, you need to enclose the key-value pairs within a pair of curly brackets "{ }".

Here is its syntax:


var identifier = { key1:value1, key2:value2 [,…..,key_n:value_n] }

Example:

void main() { 
   var userInfo = {'Username':'Jack','Password':'123@passloizenai'}; 
   print(userInfo); 
}

output −

{Username: Jack, Password: 123@passloizenai}

Dart Map<K, V>() constructor

Creates a Map instance with the default implementation, LinkedHashMap.
This constructor is equivalent to the non-const map literal &lg;K,V>{}.

A LinkedHashMap requires the keys to implement compatible operator== and hashCode, and it allows null as a key. It iterates in key insertion order.

Example:


void main() { 
   var userInfo = new Map(); 
   userInfo['Username'] = 'Jack'; 
   userInfo['Password'] = 'loizenai_password'; 
   print(details); 
} 

Output :

{Username: Jack, Password: loizenai_password}

Dart Map&lg;K, V>.from constructor


Map<K, V>.from(
Map other
)

Creates a LinkedHashMap instance that contains all key/value pairs of other.

The keys must all be instances of K and the values of V. The other map itself can have any type.
A LinkedHashMap requires the keys to implement compatible operator== and hashCode, and it allows null as a key. It iterates in key insertion order.

Example:


Map userinfo = {'username': 'Jack', 'password': '123@loizenai'};

Map _userinfo = Map.from(userinfo);
print(_userinfo);

Output:

{_username: Jack, Password: 123@loizenai}

Dart Map<K, V>.of constructor

Map<K, V>.of(
Map<K, V< other
)

Creates a LinkedHashMap with the same keys and values as other.

A LinkedHashMap requires the keys to implement compatible operator== and hashCode, and it allows null as a key. It iterates in key insertion order.

Example:


Map userinfo = {'username': 'Jack', 'password': '123@loizenai'};

Map _userinfo = Map.of(userinfo);
print(_userinfo);

Output:

{_username: Jack, Password: 123@loizenai}

Map<K, V>.fromIterable constructor

Map.fromIterable(
Iterable iterable,
    {
        K key(
            dynamic element
        ),
        V value(
            dynamic element
        )
    }
)

Creates a Map instance in which the keys and values are computed from the iterable.

The created map is a LinkedHashMap. A LinkedHashMap requires the keys to implement compatible operator== and hashCode, and it allows null as a key. It iterates in key insertion order.

For each element of the iterable this constructor computes a key/value pair, by applying key and value respectively.

The example below creates a new Map from a List. The keys of map are list values converted to strings, and the values of the map are the squares of the list values:

List<int> list = [1, 2, 3];
Map<String, int> map = new Map.fromIterable(list,
    key: (item) => item.toString(),
    value: (item) => item * item);

map['1'] + map['2']; // 1 + 4
map['3'] - map['2']; // 9 - 4

If no values are specified for key and value the default is the identity function.

In the following example, the keys and corresponding values of map are list values:


map = new Map.fromIterable(list);
map[1] + map[2]; // 1 + 2
map[3] - map[2]; // 3 - 2

The keys computed by the source iterable do not need to be unique. The last occurrence of a key will simply overwrite any previous value.

Dart Map<K, V>.fromIterables constructor


Map<K, V>.fromIterables(
    Iterable<K> keys,
    Iterable<V> values
)

Creates a Map instance associating the given keys to values.

The created map is a LinkedHashMap. A LinkedHashMap requires the keys to implement compatible operator== and hashCode, and it allows null as a key. It iterates in key insertion order.

This constructor iterates over keys and values and maps each element of keys to the corresponding element of values.

List letters = ['b', 'c'];
List<String> words = ['bad', 'cat'];
Map<String, String> map = new Map.fromIterables(letters, words);
map['b'] + map['c'];  // badcat

If keys contains the same object multiple times, the last occurrence overwrites the previous value.

The two Iterables must have the same length.

Map<K, V>.fromEntries constructor

Map<K, V>.fromEntries(
    Iterable<MapEntry<K, V>> entries
)

Creates a new map and adds all entries.
Returns a new Map where all entries of entries have been added in iteration order. If multiple entries have the same key, later occurrences overwrite the earlier ones.

Example:


Iterable someInts = [2, 7, .... ];
var squareMap = Map.fromEntries(someInts.map((n) =< MapEntry(n, n * n)));
print(squareMap[7]);  // prints 49.

Or you can filter the entries somehow:


var filteredMap = Map.fromEntries(otherMap.entries.where((e) =< e.key.isOdd));

Map<K, V>.identity constructor

Creates an identity map with the default implementation, LinkedHashMap.

An identity map uses identical for equality and identityHashCode for hash codes of keys instead of the intrinsic Object.== and Object.hashCode of the keys.

The returned map allows null as a key. It iterates in key insertion order.

Map<K, V>.unmodifiable constructor

Map<K, V>.unmodifiable(
Map other
)

Creates an unmodifiable hash based map containing the entries of other.

The keys must all be instances of K and the values of V. The other map itself can have any type.

The map requires the keys to implement compatible operator== and hashCode, and it allows null as a key. The created map iterates keys in a fixed order, preserving the order provided by other.

The resulting map behaves like the result of Map.from, except that the map returned by this constructor is not modifiable.

Example:


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

See the example:

Map<int, String> map = {1: 'one', 2: 'two'};

Map&ltString, String&gt map1 = Map.from(map); // runtime error
Map&ltString, String&gt map2 = Map.of(map);   // compilation error

– 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'

Why? -> This is because of its prototype:

Map<K, V&gt Map.from(Map<dynamic, dynamic> other)

If we pass a Map<int, String> map to the function, it converts the key-value pair type into Map<dynamic, dynamic>.

– 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<K, V> Map.of(Map&ltK, V> other)

Dart Map Get Value by Key

Example - What we do:

  • Create a Dart Map:
  • find the size of map.
  • 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 Map Foreach

  • forEach enables iterating through the Map’s entries.
Map.forEach(void f(K key, V value));
  • f(K key, V value) − Applies f to each key-value pair of the map. Calling f must not add or remove keys from the map. Return Type − void.

Example:

void main() { 
   var usrMap = {"name": "Jack", 'Email': 'jack@loizenai.com'}; 
   usrMap.forEach((k,v) => print('${k}: ${v}')); 
}

It will produce the following output −

name: Jack
Email: jack@loizenai.com 

We can use entries property and forEach() method.

map.entries.forEach((e) {
  print('{ key: ${e.key}, value: ${e.value} }');
});

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:


name
Email
Jack
jack@loizenai.com

Dart Map Add

We have 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 use addAll() method to all key/value pairs of another Map to current Map:

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}

Dart Map Update

We use one of the below solution to update a Dart Map:

  • square brackets []
  • update() method
  • update() method with ifAbsent to add a new object/entry if the input key is absent

Example Code:

Map map = {1: 'one', 2: 'two'};

map[1] = 'ONE';
print(map);

map.update(2, (v) {
  print('old value: ' + v);
  return 'TWO';
});
print(map);

map.update(3, (v) => 'Three', ifAbsent: () => 'added');
print(map);

Output:

{1: ONE, 2: two}
old value: two
{1: ONE, 2: TWO}
{1: ONE, 2: TWO, 3: added}

Remove Entry with Dart Map

Map.remove(Object key)

Parameters:
- Keys: identifies the entry to be deleted.
- Return Type: Returns the value corresponding to the specified key.

Removes key and its associated value, if present, from the map.
Returns the value associated with key before it was removed. Returns null if key was not in the map.
Note that values can be null and a returned null value doesn't always mean that the key was absent.

Example:

void main() { 
   Map m = {'name':'Tom','Id':'001'}; 
   print('Map :${m}'); 
   
   dynamic res = m.remove('name'); 
   print('Value popped from the Map :${res}'); 
}
  • Output:
Map :{name: Tom, Id: 001} 
Value popped from the Map :Tom

Dart Sort Map by Key

When we need to sort maps, we can use the SplayTreeMap. The SplayTreeMap is ordered by sorted keys.

import 'dart:collection';

void main() {
  var fruit = new SplayTreeMap();

  fruit[0] = 'Banana';
  fruit[5] = 'Plum';
  fruit[6] = 'Strawberry';
  fruit[2] = 'Orange';
  fruit[3] = 'Mango';
  fruit[4] = 'Blueberry';
  fruit[1] = 'Apple';

  print(fruit);

  fruit.forEach((key, val) {
    print('{ key: $key, value: $val}');
  });

  var sortedByValue = new SplayTreeMap.from(
      fruit, (key1, key2) => fruit[key1].compareTo(fruit[key2]));
  print(sortedByValue);
}
  • Output:
{0: Banana, 1: Apple, 2: Orange, 3: Mango, 4: Blueberry, 5: Plum, 6: Strawberry}
{ key: 0, value: Banana}
{ key: 1, value: Apple}
{ key: 2, value: Orange}
{ key: 3, value: Mango}
{ key: 4, value: Blueberry}
{ key: 5, value: Plum}
{ key: 6, value: Strawberry}

Dart Convert Map to List

Create a Customer model:

class Customer {
  String name;
  int age;

  Customer(this.name, this.age);

  @override
  String toString() {
    return '{ ${this.name}, ${this.age} }';
  }
}

Create a Dart Map:

Map map = {'Jane': 21, 'Mary': 43, 'Peter': 13};
  • Using Map forEach() method:
map.forEach((k, v) => list.add(Customer(k, v)));
print(list);

Output:

[{ Jane, 21 }, { Mary, 43 }, { Peter, 13 }]
  • Using Iterable forEach() method:
map.entries.forEach((e) => list.add(Customer(e.key, e.value)));
print(list);
  • Using Iterable map() method:
list = map.entries.map((e) => Customer(e.key, e.value)).toList();

Dart Sort Map by Value

Continue with above example, we create a sorted map by values from the original map. We pass the from function a comparison function, which compares the values of the pairs.

var sortedByValue = new SplayTreeMap.from(
    fruit, (key1, key2) => fruit[key1].compareTo(fruit[key2]));
    
print(sortedByValue);
  • Output:
{1: Apple, 0: Banana, 4: Blueberry, 3: Mango, 2: Orange, 5: Plum, 6: Strawberry}

Related posts

Related posts:


Read more at here

Top comments (1)

Collapse
 
mmanflori profile image
flutterCode

Great work. thank you !