简体   繁体   中英

How do I Map a List of Maps into a List of my Custom Class?

I am trying to map a List of Maps into a List of Objects of my Custom "Address" Class. However, if I run my code, i get this error:

I/flutter (26434): type 'CastList<dynamic, List<Address>>' is not a subtype of type 'List<Address>'

This is my SourceCode: listOfMaps is the List of Maps I pull from a database;

List<Address> _userAddresses;
_userAddresses = listOfMaps.map((address) {
    return Address(
      firstName: address["firstName"],
      lastName: address["lastName"],
      streetname: address["streetname"],
      houseNumber: address["houseNumber"],
      zipCode: address["zipCode"],
      city: address["city"],
      country: address["country"],
      state: address["state"],
    );
  }).toList().cast<List<Address>>();

I'm supposing listOfMaps is List<dynamic> then you can do this:

var _userAddresses = listOfMaps.map<Address>((m) => Address.fromJson(m)).toList();

Where:

Address.fromJson(Map<String, dynamic> jdata) { ... }

I hope it to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM