Map.from()
и Map.of()
перенаправляются на LinkedHashMap<K, V>.from
и LinkedHashMap<K, V>.of
соответственно. Ниже приведен исходный код .from()
и .of()
LinkedHashMap.
/// Creates a [LinkedHashMap] that contains all key value pairs of [other].
///
/// The keys must all be instances of [K] and the values to [V].
/// The [other] map itself can have any type.
factory LinkedHashMap.from(Map other) {
LinkedHashMap<K, V> result = LinkedHashMap<K, V>();
other.forEach((k, v) {
result[k] = v;
});
return result;
}
/// Creates a [LinkedHashMap] that contains all key value pairs of [other].
factory LinkedHashMap.of(Map<K, V> other) =>
LinkedHashMap<K, V>()..addAll(other);
Как написано в комментариях и как видно из кода, .from()
принимает карту с любым ключом / значением типы, тогда как .of()
может принимать только Map<K, V>
.
void main() async {
Map<String, int> map1 = {'zero': 0, 'one': 1, 'two': 2};
final map2 = Map<String, double>.from(map1);
print(map2); // {'zero': 0, 'one': 1, 'two': 2}
/*
// This fails because the passed map is not Map<String, double> but Map<String, int>.
final map2 = Map<String, double>.of(map1);
*/
final map3 = Map<String, int>.of(map1);
print(map3); // {'zero': 0, 'one': 1, 'two': 2}
}