How to cast <dynamic> to List<String>?

筅森魡賤 提交于 2020-12-12 11:46:27

问题


I have a record class to parse objects coming from Firestore. A stripped down version of my class looks like:

class BusinessRecord {
  BusinessRecord.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        name = map['name'] as String,
        categories = map['categories'] as List<String>;

  BusinessRecord.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  final String name;
  final DocumentReference reference;
  final List<String> categories;
}

This compiles fine, but when it runs I get a runtime error:

type List<dynamic> is not a subtype of type 'List<String>' in type cast

If I just use categories = map['categories']; I get a compile error: The initializer type 'dynamic' can't be assigned to the field type 'List<String>'.

categories on my Firestore object is a List of strings. How do I properly cast this?

Edit: Following is what the exception looks like when I use the code that actually compiles:


回答1:


Imho, you shouldn't cast the list, instead cast its children one by one, for example:

UPDATE

...
...
categories = (map['categories'] as List)?.map((item) => item as String)?.toList();
...
...



来源:https://stackoverflow.com/questions/60105956/how-to-cast-dynamic-to-liststring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!