flutter 如何将列表转换< dynamic>为列表< String>?

qybjjes1  于 2023-06-07  发布在  Flutter
关注(0)|答案(7)|浏览(1047)

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

qrjkbowd

qrjkbowd1#

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

更新

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

dfddblmv

dfddblmv2#

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

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

请注意,“as List”可能甚至不需要。

xzv2uavs

xzv2uavs3#

简单答案:

您可以使用扩展运算符,如[...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]
moiiocjp

moiiocjp4#

如果你想将dynamic转换为String,就把它放在这里:

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

List<String> strlist = dynamiclist.cast<String>();
cygmwpex

cygmwpex5#

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

rjjhvcjd

rjjhvcjd6#

List<String>? categoriesList = (map['categories'] as List)?.cast<String>()
fd3cxomn

fd3cxomn7#

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

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;
  }

相关问题