How do I convert Map<String, dynamic>
To Map<String, double
in Flutter>? What commands are there?
CodePudding user response:
You can use the castFrom
method like this:
final output = Map.castFrom<String, dynamic, String, double>(input);
Where input
is of type Map<String, dynamic>
and output
will be of type Map<String, double>
.
CodePudding user response:
Instead of casting I prefer this way to avoid getting runtime error.
void main(List<String> args) {
Map<String, dynamic> data = {
"A": 3,
"b": "4",
"c": null,
"d": 2.4,
};
final Map<String, double> result = Map.fromIterables(
data.keys,
data.values.map((e) => (double.tryParse(e.toString()) ?? 0.0)),
);
print(result); //{A: 3.0, b: 4.0, c: 0.0, d: 2.4}
}
More about Map