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

Flutter写入Firestore报错:Set<Map<String,dynamic>>无法赋值给Map参数

问题:Firestore写入用户数据时类型不匹配报错

问题场景

定义了自定义用户模型CustomUser,其toMap()方法代码如下:

Map<String, dynamic> toMap() {
    return {
      'uid': uid,
      'email': email,
      'firstName': firstName,
    };
  }

在注册方法中调用该方法写入Firestore时,代码如下:

Future<void> signUp({
    required String email,
    required String firstName,
    required String password,
  }) async {
    try {
      final fbAuth.UserCredential userCredential = await firebaseAuth
          .createUserWithEmailAndPassword(email: email, password: password);
      final signedInUser = userCredential.user!;

      CustomUser customUser = CustomUser(
        uid: signedInUser.uid,
        email: email,
        firstName: firstName,
      );
      await userRef.doc(signedInUser.uid).set({
        customUser.toMap()
      });
    } catch (e) {
      throw CustomError(
        code: 'Exception',
        message: e.toString(),
        plugin: 'Flutter Error / Server Error',
      );
    }
  }

运行后出现报错:Set<Map<String, dynamic>> can't be assigned to the parameter type 'Map<String, dynamic>',但直接在set()中写'uid': uid, 'email': email这类键值对时,方法能正常运行。

问题原因

问题不在toMap()方法本身,而是调用set()时的写法错误:

  • 你写的{customUser.toMap()}在Dart中会被解析为Set字面量(大括号内只有单个表达式,没有键值对结构),最终生成的是一个包含Map元素的Set类型对象。
  • 而Firestore的set()方法要求传入的参数必须是Map<String, dynamic>类型,因此出现类型不匹配的报错。
  • 直接写键值对时,{'uid': uid, ...}是标准的Map字面量,符合参数类型要求,所以能正常执行。

解决方法

去掉set()方法参数外层的大括号,直接传入toMap()的返回值即可:

await userRef.doc(signedInUser.uid).set(customUser.toMap());

内容的提问来源于stack exchange,提问作者greenzebra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:22:43