【问题标题】:dart/flutter casting dynamic list from Future.wait causing type 'List<dynamic>' is not a subtype of type 'List<CustomClass>'来自 Future.wait 的 dart/flutter 铸造动态列表导致类型“List<dynamic>”不是“List<CustomClass>”类型的子类型
【发布时间】:2023-03-25 07:56:02
【问题描述】:

在我的应用程序中获取一些数据是使用Future.wait&lt;T&gt; 完成的。一个问题是它只适用于一种数据类型,因此在其中运行一些使用数据类型的期货将导致您必须将返回结果列表中的每个结果转换为适当的类型。

我面临的问题始于Future.wait,专门处理来自Future 的多个结果。

下面使用的函数签名,用于上下文:

Future<List<QueryDocumentSnapshot<ProfileConversationPreference>>> getProfileConversationsOnce({String? uid});

未来的电话:

var result = await Future.wait<dynamic>([
  //...
  profileService.getProfileConversationsOnce(uid: uid), // 6
  //...
]);

当future返回时,要得到getProfileConversationsOnce的结果,我需要使用result[6](结果的索引)

问题:

要将结果分配给适当的列表,我需要将其从List&lt;dynamic&gt; 转换为List&lt;QueryDocumentSnapshot&lt;ProfileConversationPreference&gt;&gt;。根据this notable SO post,应该使用cast&lt;&gt;() 函数。

在一个函数中使用此强制转换时,它不起作用并引发以下错误:

conversationList = (result[6] ?? []).cast<QueryDocumentSnapshot<ProfileConversationPreference>>().map((e) => e.data()).toList();

错误:

I/flutter (12257): type 'List<dynamic>' is not a subtype of type 'List<ProfileConversationPreference>'

但是在分解这个演员表时,它可以正常工作:

  List s = (result[6] ?? []);
  List<QueryDocumentSnapshot<ProfileConversationPreference>> ss = s.cast<QueryDocumentSnapshot<ProfileConversationPreference>>();
  conversationList = ss.map((e) => e.data()).toList();

更多详情:

我正在运行的代码示例:

List<ProfileConversationPreference> conversationList = [];
try {
 // this works, at each step I can view the content and it is processed correctly - it is a broken up version of the single line below
  List s = (result[6] ?? []);
  List<QueryDocumentSnapshot<ProfileConversationPreference>> ss = s.cast<QueryDocumentSnapshot<ProfileConversationPreference>>();
  conversationList = ss.map((e) => e.data()).toList();

  // this does NOT WORK
  conversationList = (result[6] ?? []).cast<QueryDocumentSnapshot<ProfileConversationPreference>>().map((e) => e.data()).toList();
} catch (e) {
  print(e);
}

【问题讨论】:

  • 我们不会这样投
  • @nitishk72 那么怎么投呢?
  • 给我看这个类 ProfileConversationPreference

标签: firebase flutter dart casting future


【解决方案1】:

来自此链接 (github dart-lang issues) 的解决方案解决了一个问题:Effective Dart:何时使用“as”、“.retype”、“.cast”

因此,我使用了List&lt;T&gt;.from()

解决方案

List<QueryDocumentSnapshot<ProfileConversationPreference>>.from(result[6] ?? []).map((e) => e.data()).toList()

【讨论】:

    【解决方案2】:

    ...或者你可以作弊一点:

    List<ProfileConversationPreference> conversationList = [];
    
    await Future.wait([
      //...
      () async { 
           conversationList = await profileService.getProfileConversationsOnce(uid: uid); 
      }(),
      //...
    ]);
    

    如果您可以为所有未来执行此操作,则可以跳过结果数组和强制转换。

    【讨论】:

    • 为 9 个期货这样做感觉...错误 - 但是,你是对的
    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多