【发布时间】:2023-03-25 07:56:02
【问题描述】:
在我的应用程序中获取一些数据是使用Future.wait<T> 完成的。一个问题是它只适用于一种数据类型,因此在其中运行一些使用数据类型的期货将导致您必须将返回结果列表中的每个结果转换为适当的类型。
我面临的问题始于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<dynamic> 转换为List<QueryDocumentSnapshot<ProfileConversationPreference>>。根据this notable SO post,应该使用cast<>() 函数。
在一个函数中使用此强制转换时,它不起作用并引发以下错误:
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