前提
業務でFlutter×Firebaseでアプリ開発を行なっています。
DBはFirestoreを利用しているのですが、仕様上数値型の扱いが不安定なことがあり
Firestoreに格納するデータはnum型に統一し、アプリでint/doubl型にキャストする、という手法を採用しています。
単一のデータのキャストはシンプルな処理ではあるのですが、
Map型をキャストしたい際にやや手こずったため、備忘録として残します。
結論
以下で解決します。
// 宣言
Map<String,num> examples;
// Mapに含まれているkeyのリストのkeysとvalueのリストのvaluesをそれぞれ取り出し、
// valuesに対してtoDouble()でキャストします。
Map.fromIterables(examples.keys,
examples.values.toList().map((e) => e.toDouble()).toList())
// Map.fromIterablesの定義はこちら
Creates a map associating the given [keys] to the given [values].
The map construction iterates over [keys] and [values] simultaneously,
and adds an entry to the map for each pair of key and value.
If [keys] contains the same object multiple times, the value of the last occurrence overwrites any previous value.
The two [Iterable]s must have the same length.
The created map is a [LinkedHashMap]. A LinkedHashMap requires the keys to implement compatible operator== and hashCode. It iterates in key insertion order.
List<String> letters = ['b', 'c'];
List<String> words = ['bad', 'cat'];
var map = Map.fromIterables(letters, words);
参考