You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:42:55