Flutter(Android Studio)用户存储代码报错求助:参数类型不匹配
问题解决:Firestore add()方法回调类型不匹配错误
错误出在then()的回调函数上——Firestore的add()方法执行成功后,会返回一个DocumentReference对象,要求then()的回调函数必须接收这个对象作为参数,但你写的then(() { ... })是无参函数,类型不匹配导致报错。
以下是两种可行的解决方法:
方案1:给回调函数添加参数
即使不需要使用返回的DocumentReference,也得在回调里声明它,满足类型要求:
class UserManagement { storeNewUser(user, context) async { await FirebaseFirestore.instance.collection('/users').add({ 'email': user.email, 'uid': user.id, }).then((docRef) { // 添加docRef参数匹配类型 Navigator.of(context).pop(); Navigator.of(context).pushReplacementNamed(HomePage.id); }).catchError((e) { print(e); }); } }
方案2:改用纯async/await写法(更推荐)
既然已经使用async关键字,直接用await处理异步操作,代码更简洁易读,还能避免then链的类型问题:
class UserManagement { storeNewUser(user, context) async { try { await FirebaseFirestore.instance.collection('/users').add({ 'email': user.email, 'uid': user.id, }); Navigator.of(context).pop(); Navigator.of(context).pushReplacementNamed(HomePage.id); } catch (e) { print(e); } } }
内容的提问来源于stack exchange,提问作者abraham seifu
相关产品推荐
相关产品推荐

