Working with lists and maps in Dart is common. Sometimes you need to make a copy of one without changing the original. Here are several methods you can use.
Simple Ways to Copy
Using JSON encode/decode
This method creates a clone without reference by converting the list or map to a JSON string and then parsing it back.
import 'dart:convert';
List newList = json.decode(json.encode(oldList));
Map newMap = json.decode(json.encode(oldMap));
Using the Spread Operator (...)
Another way to clone without reference, often considered more readable and direct for simple cases.
List newList = [...oldList];
Map newMap = {...oldMap};
// For HashMap specifically
// HashMap newMap = HashMap.from({...oldMap});
Using the from
Factory
This method creates a new list or map by copying values from the original. Note that for complex objects within the list/map, it might still copy references (shallow copy).
List newList = List.from(oldList);
Map newMap = Map.from(oldMap);
Using ..addAll
Similar to from
, this method adds all elements from the original list to a new list. It's also a shallow copy.
List newList = []..addAll(oldList);
// For Map: Map newMap = {}..addAll(oldMap);
Using Packages for Specific Needs
Using Google built_collection package
This package is for creating immutable collections. It doesn't make an immediate deep copy but provides a copy-on-write wrapper and methods for rebuilding.
// Requires built_collection package
// var builtList = [1, 2, 3].build();
// builtList = builtList.rebuild((b) => b..addAll([7, 6, 5]));
Using package fast_immutable_collections
Another package for immutable collections. Provides immutable types like IList
and IMap
which are inherently "copied" when modified, as operations return new instances.
// Requires fast_immutable_collections package
// final IList<String> oldList; // example immutable list
// var newList = IList.orNull(oldList); // creates a new immutable list pointing to the same data initially
Choose the method that best fits your needs, considering if you need a deep clone, the performance implications, and if you are working with mutable or immutable collections.