Flutter调用返回int的Future异步函数写入Firestore崩溃如何解决
错误原因
- 你定义的
getID()是返回Future<int>的异步函数,不使用await调用的情况下拿到的是Future实例而非实际的int值,Firestore无法序列化Future类型数据,因此触发崩溃 - 额外优化点:
getID()末尾的return await currentID不需要加await,currentID已经是同步的int值,直接返回即可
修正后的代码
1. 优化getID函数
Future<int> getID() async { DocumentSnapshot idSnapshot = await FirebaseFirestore.instance .collection("Bestellungen") .doc("default") .get(); int currentID = idSnapshot["id"] + 1; // 去掉不必要的await return currentID; }
2. 修正onTap回调
给onTap的匿名函数加上async关键字,即可在内部使用await调用异步函数:
onTap: () async { Scaffold.of(context).hideCurrentSnackBar(); // 先await拿到id值 int id = await getID(); await FirebaseFirestore.instance .collection("Bestellungen") .add({ "id": id, "item": document["titel"], "done": false, "time": getTime(), }); }
补充注意事项
- 如果需要处理异步调用过程中的异常,可以在
onTap内部套try-catch捕获网络请求、数据解析相关的错误 - 若
getTime()同样是异步函数,也需要用await拿到返回值后再传入集合数据中
内容的提问来源于stack exchange,提问作者Thoxh
相关产品推荐
相关产品推荐

