【发布时间】:2020-05-23 03:33:03
【问题描述】:
我有一个记录类来解析来自 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>'。
我的 Firestore 对象上的categories 是一个字符串列表。我该如何正确投射?
编辑:以下是我使用实际编译的代码时的异常情况:
【问题讨论】: