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:
List newList = json.decode(json.encode(oldList));
Map newMap = json.decode(json.encode(oldMap));
Example:
import 'dart:convert';
void main(){
// Define a multi-dimensional map
final Map oldMap = {
"name" : {
"first": "Joh",
"last": "Doe"
},
"asset" : {
"money" : {
"bank": 1000,
"cash": 100
},
"house": 1
}
};
final Map newMap = json.decode(json.encode(oldMap));
newMap["name"]["first"] = "Jesse";
newMap["name"]["last"] = "Pinkman";
newMap["asset"]["money"]["cash"] = 0;
print('oldMap: $oldMap');
print('newMap: $newMap');
}
Output:
oldMap: {
name: {first: Joh, last: Doe},
asset: {
money: {bank: 1000, cash: 100},
house: 1
}
}
newMap: {
name: {first: Jesse, last: Pinkman},
asset: {
money: {bank: 1000, cash: 0},
house: 1
}
}
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:
List newList = [...oldList];
Map newMap = {...oldMap}
Example:
void main(){
// List
final List myList = ['A', 'B', 'C', 'D'];
final List clonedList = [...myList];
clonedList[0] = 'Dog';
print('myList: $myList');
print('clonedList: $clonedList');
// Map
final Map myMap = {
'name': 'John',
'age': 37
};
final Map clonedMap = {...myMap};
clonedMap["name"] = "Marry";
clonedMap['age'] = 4;
print('myMap: $myMap');
print('clonedMap: $clonedMap');
}
Output:
myList: [A, B, C, D]
clonedList: [Dog, B, C, D]
myMap: {name: John, age: 37}
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:
List newList = List.from(oldList);
Map newMap = Map.from(oldMap);
Using []..addAll()
This approach is quick and good for only one-dimensional lists.
Syntax:
List newList = []..addAll(oldList);
Example:
void main(){
List oldList = [1, 2, 3];
List newList = []..addAll(oldList);
newList[2] = 100;
print('oldList: $oldList');
print('newList: $newList');
}
Output:
oldList: [1, 2, 3]
newList: [1, 2, 100]