0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Flutter/Dart】Map<String, num>型をMap<String, double>/Map<String, int>にキャストする方法

0
Last updated at Posted at 2021-07-03

前提

業務で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);

参考

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?