Matt Takao
Matt Takao

Reputation: 2996

Dart: convert Map to List of Objects

Did several google searches, nothing helpful came up. Been banging my head against some errors when trying to do something that should be pretty simple. Convert a map such as {2019-07-26 15:08:42.889861: 150, 2019-07-27 10:26:28.909330: 182} into a list of objects with the format:

class Weight {
  final DateTime date;
  final double weight;
  bool selected = false;

  Weight(this.date, this.weight);
}

I've tried things like: List<Weight> weightData = weights.map((key, value) => Weight(key, value));

There's no toList() method for maps, apparently. So far I'm not loving maps in dart. Nomenclature is confusing between the object type map and the map function. Makes troubleshooting on the internet excruciating.

Upvotes: 82

Views: 161396

Answers (11)

Azhar Ali
Azhar Ali

Reputation: 2436

Object Class

class ExampleObject {
  String variable1;
  String variable2;

  ExampleObject({
    required this.variable1,
    required this.variable2,
  });

  Map<String, dynamic> toMap() {
    return {
      'variable1': this.variable1,
      'variable2': this.variable2,
    };
  }

  factory ExampleObject.fromMap(Map<String, dynamic> map) {
    return ExampleObject(
      variable1: map['variable1'] as String,
      variable2: map['variable2'] as String,
    );
  }
}

Convert Map to Object List

List<ExampleObject> objectList = List<ExampleObject>.from(mapDataList.map((x) => ExampleObject.fromMap(x)));

Upvotes: 1

Maksim Gridin
Maksim Gridin

Reputation: 187

If you need to convert Map values to a list, the simplest oneline code looks like this:

final list = map.values.toList(); 

Upvotes: 7

Christian Findlay
Christian Findlay

Reputation: 7672

You simply don't need to. the values property is an Iterable<> of your objects. You can iterate over this or you can convert it to a list. For example,

// ignore_for_file: avoid_print

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets("convert Map to List of Objects", (tester) async {
    final weight1 = Weight(const ValueKey("1"), DateTime.now(), 1);
    final weight2 = Weight(const ValueKey("2"), DateTime.now(), 2);

    final map = {weight1.key: weight1, weight2.key: weight2};

    //You don't have to convert this to a list
    //But you can if you want to
    final list = map.values.toList();

    list.forEach((w) => print("Key: ${w.key} Weight: ${w.weight} "));
  });
}

class Weight {
  final Key key;
  final DateTime date;
  final double weight;
  bool selected = false;

  Weight(this.key, this.date, this.weight);
}

Upvotes: 0

Vasily  Bodnarchuk
Vasily Bodnarchuk

Reputation: 25294

Details

  • Flutter 1.26.0-18.0.pre.106

Solution

/libs/extensions/map.dart

extension ListFromMap<Key, Element> on Map<Key, Element> {
  List<T> toList<T>(
          T Function(MapEntry<Key, Element> entry) getElement) =>
      entries.map(getElement).toList();
}

Usage

import 'package:myApp/libs/extensions/map.dart';

final map = {'a': 1, 'b': 2};
print(map.toList((e) => e.value));
print(map.toList((e) => e.key));

Upvotes: 6

Rithvik Nishad
Rithvik Nishad

Reputation: 565

You can also use a for collection to achieve the same.

var list = [for (var e in map.entries) FooClass(e.key, e.value)];

Upvotes: 7

shivanand naduvin
shivanand naduvin

Reputation: 380

You can do this:

List<Weight> weightData = (weights as List ?? []).map((key, value) => Weight(key,value)).toList()

or you can try:

List<Weight> weightData = List.from(weights.map((key, value) => Weight(key, value)))

Upvotes: 2

Feisal  Aswad
Feisal Aswad

Reputation: 455

Vidor answer is correct .any way this worked for me

      List<String> list = new List();
  userDetails.forEach((k, v) => list.add(userDetails[k].toString()));

Upvotes: 1

ybakos
ybakos

Reputation: 8630

Following on Richard Heap's comment above, I would:

List<Weight> weightData =
  mapData.entries.map( (entry) => Weight(entry.key, entry.value)).toList();

Don't forget to call toList, as Dart's map returns a kind of Iterable.

Upvotes: 170

atreeon
atreeon

Reputation: 24087

Use the entries property on the map object

This returns a List of type MapEntry<key,value>.

myMap.entries.map((entry) => "${entry.key} + ${entry.value}").toList();

Upvotes: 7

Waqas
Waqas

Reputation: 141

Sometimes the typecast will fail and you can enforce it by doing:

List<Weight> weightData =
  weightData.entries.map<Weight>( (entry) => Weight(entry.key, entry.value)).toList();

Example from my project where it wasn't working without typecast:

List<NetworkOption> networkOptions = response.data['data']['networks']
          .map<NetworkOption>((x) => NetworkOption.fromJson(x))
          .toList();

Upvotes: 14

Pushan Gupta
Pushan Gupta

Reputation: 3825

List<Weight> weightData = List();

weights.forEach((k,v) => weightData.add(Weight(k,v))); 

Upvotes: 19

Related Questions