Using json.decode() and json.encode()

This approach works in any scenario (nested lists, nested maps…). You can actually clone multi-dimensional lists and maps without references.
Syntax:

  1. List newList = json.decode(json.encode(oldList));
  2. Map newMap = json.decode(json.encode(oldMap));

Example:

  1. import 'dart:convert';
  2. void main(){
  3. // Define a multi-dimensional map
  4. final Map oldMap = {
  5. "name" : {
  6. "first": "Joh",
  7. "last": "Doe"
  8. },
  9. "asset" : {
  10. "money" : {
  11. "bank": 1000,
  12. "cash": 100
  13. },
  14. "house": 1
  15. }
  16. };
  17. final Map newMap = json.decode(json.encode(oldMap));
  18. newMap["name"]["first"] = "Jesse";
  19. newMap["name"]["last"] = "Pinkman";
  20. newMap["asset"]["money"]["cash"] = 0;
  21. print('oldMap: $oldMap');
  22. print('newMap: $newMap');
  23. }

Output:

  1. oldMap: {
  2. name: {first: Joh, last: Doe},
  3. asset: {
  4. money: {bank: 1000, cash: 100},
  5. house: 1
  6. }
  7. }
  8. newMap: {
  9. name: {first: Jesse, last: Pinkman},
  10. asset: {
  11. money: {bank: 1000, cash: 0},
  12. house: 1
  13. }
  14. }

Using the spread syntax

This approach is quick and convenient for one-dimensional lists and maps. :::success Note: This method works with a one-dimensional List or Map. For cloning a multi-dimensional (nested) List or Map, use the first method. :::

Syntax:

  1. List newList = [...oldList];
  2. Map newMap = {...oldMap}


Example:

  1. void main(){
  2. // List
  3. final List myList = ['A', 'B', 'C', 'D'];
  4. final List clonedList = [...myList];
  5. clonedList[0] = 'Dog';
  6. print('myList: $myList');
  7. print('clonedList: $clonedList');
  8. // Map
  9. final Map myMap = {
  10. 'name': 'John',
  11. 'age': 37
  12. };
  13. final Map clonedMap = {...myMap};
  14. clonedMap["name"] = "Marry";
  15. clonedMap['age'] = 4;
  16. print('myMap: $myMap');
  17. print('clonedMap: $clonedMap');
  18. }

Output:

  1. myList: [A, B, C, D]
  2. clonedList: [Dog, B, C, D]
  3. myMap: {name: John, age: 37}
  4. clonedMap: {name: Marry, age: 4}

Using the from() method

As the second approach, this one is quick and good for one-dimensional lists and maps. :::success Note: This method works with a one-dimensional List or Map. For cloning a multi-dimensional (nested) List or Map, use the first method. :::

Syntax:

  1. List newList = List.from(oldList);
  2. Map newMap = Map.from(oldMap);

Using []..addAll()

This approach is quick and good for only one-dimensional lists.

Syntax:

  1. List newList = []..addAll(oldList);

Example:

  1. void main(){
  2. List oldList = [1, 2, 3];
  3. List newList = []..addAll(oldList);
  4. newList[2] = 100;
  5. print('oldList: $oldList');
  6. print('newList: $newList');
  7. }

Output:

  1. oldList: [1, 2, 3]
  2. newList: [1, 2, 100]