我有一个记录类来解析来自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是一个字符串列表.我该如何恰当地铸造这个呢?

编辑:以下是当我使用实际编译的代码时异常的样子:

VSCode Exception

推荐答案

Imho,你不应该播放列表,而是一个接一个地播放它的子项,例如:

UPDATE

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

enter image description here

Dart相关问答推荐

S,返回Future.sync()的函数和不需要等待的异步函数有什么区别?

我不明白在DART的`if()`语句中使用`case

Dart中的运算符(){…}做什么?

程序给出不准确的值

将 Stream> 转换为 Stream

polymer.dart 中的@observable 和@published 有什么区别?

Dart 扩展: don't access members with "this" unless avoiding shadowing

在 Dart 的 Cloud Firestore 中添加文档后如何获取文档 ID

Angular Dart 和 Polymer Dart 的区别

如何防止多行文本小部件放置在行中时被剪裁?

dart:js 和 js 包有什么区别?

Flatter中的Sqlite,数据库assets如何工作

Flutter热重新加载和热重启不工作

摆动中的可滚动导轨

参数类型PointerEvent不能分配给参数类型PointerDownEvent

更新复选框并从Flutter对话框中返回值

如何提高数据与二进制数据转换的 Dart 性能?

在 Dart 中升序和降序排序?

Dart 会支持服务器端开发吗?

在 Dart 中,bool是否有parse,就像int一样?