我有一个记录类来解析来自 Firestore 的对象。我的课程的精简版本如下所示:
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;
}
这编译得很好,但是当它运行时我得到一个运行时错误:
type List<dynamic> is not a subtype of type 'List<String>' in type cast
如果我只是使用categories = map['categories'];
我收到编译错误:The initializer type 'dynamic' can't be assigned to the field type 'List<String>'
.
categories
我的 Firestore 对象上是一个字符串列表。我如何正确地投射这个?
编辑:以下是当我使用实际编译的代码时异常的样子:
恕我直言,您不应该强制转换列表,而应将其子级一一强制转换,例如:
UPDATE
...
...
categories = (map['categories'] as List)?.map((item) => item as String)?.toList();
...
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)