如何将 <dynamic> 转换为 List<String>?

ggu*_*erg 7 dart flutter

我有一个记录类来解析来自 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;
}
Run Code Online (Sandbox Code Playgroud)

这编译得很好,但是当它运行时我得到一个运行时错误:

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 对象上是一个字符串列表。我如何正确投射这个?

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

VSCode 异常

Ter*_*iel 53

更简单的答案,据我所知也是建议的方式。

List<String> categoriesList = List<String>.from(map['categories'] as List);

Run Code Online (Sandbox Code Playgroud)

请注意,“as List”可能根本不需要。

  • 如果有人的地图可能有空值,只想添加到此 --- &gt;&gt;&gt; List&lt;String&gt;.from(map["categories"] ??= []) &lt;&lt;--- 在我的情况下,当添加新的Firebase 文档的字段以前的文档没有类别,因此为空。 (2认同)

Hia*_*ian 13

恕我直言,你不应该投射列表,而是一个一个地投射它的孩子,例如:

更新

...
...
categories = (map['categories'] as List)?.map((item) => item as String)?.toList();
...
...
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


enc*_*nce 13

只是为了把它放在那里,如果你想投射dynamicString

List dynamiclist = ['hello', 'world'];

List<String> strlist = dynamiclist.cast<String>();
Run Code Online (Sandbox Code Playgroud)


use*_*613 7

快速回答:

您可以使用扩展运算符,例如[...json["data"]].

完整示例:

final Map<dynamic, dynamic> json = {
  "name": "alice",
  "data": ["foo", "bar", "baz"],
};

// method 1, cast while mapping:
final data1 = (json["data"] as List)?.map((e) => e as String)?.toList();
print("method 1 prints: $data1");

// method 2, use spread operator:
final data2 = [...json["data"]];
print("method 2 prints: $data2");
Run Code Online (Sandbox Code Playgroud)

输出:

flutter: method 1 prints: [foo, bar, baz]
flutter: method 2 prints: [foo, bar, baz]
Run Code Online (Sandbox Code Playgroud)