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

t1qtbnec  于 2022-11-17  发布在  Flutter
关注(0)|答案(5)|浏览(287)

我有一个记录类来解析来自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是一个字符串列表。我如何正确地转换它?
编辑:下面是当我使用实际编译的代码时异常的样子:

3bygqnnd

3bygqnnd1#

Imho,您不应该强制转换列表,而是一个接一个地强制转换它的子项,例如:

更新

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

raogr8fs

raogr8fs2#

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

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

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

w8f9ii69

w8f9ii693#

简单答案:

您可以使用spread运算子,例如[...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");

输出量:

flutter: method 1 prints: [foo, bar, baz]
flutter: method 2 prints: [foo, bar, baz]
khbbv19g

khbbv19g4#

final list = List<String>.from(await value.get("paymentCycle"));
当我从Firebase获取数据时,我使用了此功能

gj3fmq9x

gj3fmq9x5#

如果您启用了“隐式动态”,则接受的答案实际上不起作用。
也不容易读懂。
转换的完整型别版本为:

List<String> categories = jsonToList(json['categories']);

将以下函数放在帮助器库中,您就拥有了一个类型安全、可重用且易于阅读的解决方案。

Set<T> jsonToSet<T>(Object? responseData) {
    final temp = responseData as List? ?? <dynamic>[];
    final set = <T>{};
    for (final tmp in temp) {
      set.add(tmp as T);
    }
    return set;
  }

  List<T> jsonToList<T>(Object? responseData) {
    final temp = responseData as List? ?? <dynamic>[];
    final list = <T>[];
    for (final tmp in temp) {
      list.add(tmp as T);
    }
    return list;
  }

相关问题