Flutter应用Firebase创建用户时Firestore未写入的类型转换问题
问题现象
使用Firebase创建用户时,Firebase认证已成功生成用户,但用户数据未写入Firestore,同时控制台抛出类型转换错误。
错误日志
W/System ( 9991): Ignoring header X-Firebase-Locale because its value was null.
W/System ( 9991): Ignoring header X-Firebase-Locale because its value was null.
I/tergooglesigni( 9991): Background concurrent copying GC freed 63914(2787KB) AllocSpace objects, 9(308KB) LOS objects, 49% free, 3305KB/6611KB, paused 965us total 100.504ms
D/FirebaseAuth( 9991): Notifying id token listeners about user ( WsAb4Bc7dEgbw3FQdmsRQZbWMQZ2 ).
D/FirebaseAuth( 9991): Notifying auth state listeners about user ( WsAb4Bc7dEgbw3FQdmsRQZbWMQZ2 ).
I/flutter ( 9991): Error occurred: Error: type 'List<Object?>' is not a subtype of type 'PigeonUserDetails?' in type cast
I/flutter ( 9991): <<<-----------------------------------------------: Error: type 'List<Object?>' is not a subtype of type 'PigeonUserDetails?' in type cast--------------------------------------------->>>
F/crash_dump32(13059): crash_dump.cpp:474] failed to attach to thread 180: Permission denied
I/tergooglesigni( 9991): Thread[6,tid=10003,WaitingInMainSignalCatcherLoop,Thread*=0x9b400e10,peer=0xa06401e8,"Signal Catcher"]: reacting to signal 3
I/tergooglesigni( 9991):
I/libc ( 9991): Requested dump for tid 9991 (tergooglesignin)
I/tergooglesigni( 9991): Wrote stack traces to tombstoned
相关代码(authentication.dart)
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; class AuthServices { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; Future<String> signupUser({ required String name, required String email, required String password, }) async { if (name.isEmpty || email.isEmpty || password.isEmpty) { return "Error: Invalid input parameters"; } String res = "An error occurred"; // Default error message try { // Create a new user with email and password UserCredential userCredential = await _firebaseAuth .createUserWithEmailAndPassword(email: email, password: password); if (userCredential.user != null) { String uid = userCredential.user!.uid; print("User ID: $uid"); // Add user details to Firestore under 'users' collection await _firestore.collection("users").doc(uid).set({ 'name': name, 'email': email, 'uid': uid, }); print("Successfully added to Firestore"); res = "Successfully executed"; } else { res = "User creation failed: user is null"; print("Error: User creation failed"); } } catch (e) { // Log detailed error message res = "Error: ${e.toString()}"; print("Error occurred: $res"); } print("<<<-----------------------------------------------: $res--------------------------------------------->>>"); return res; } }
解决方案
- 核心原因:错误
'List<Object?>' is not a subtype of type 'PigeonUserDetails?'由Firebase依赖版本不兼容导致,Pigeon是Firebase内部跨平台通信工具,版本冲突会引发类型转换异常。
更新Firebase依赖到兼容版本
在pubspec.yaml中,将所有Firebase相关依赖更新至最新稳定版,示例如下:firebase_core: ^2.24.2 firebase_auth: ^4.16.0 cloud_firestore: ^4.15.0清理缓存并重新获取依赖
执行以下命令清除旧缓存,重新下载依赖:flutter clean flutter pub get验证Firestore安全规则
确保Firestore允许认证用户创建自己的文档,测试阶段可临时使用以下规则:rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow create: if request.auth != null && request.auth.uid == userId; } } }添加Firestore写入单独异常捕获
修改代码中写入Firestore的部分,单独捕获异常,明确是否在写入环节出现问题:if (userCredential.user != null) { String uid = userCredential.user!.uid; print("User ID: $uid"); // Add user details to Firestore under 'users' collection try { await _firestore.collection("users").doc(uid).set({ 'name': name, 'email': email, 'uid': uid, }); print("Successfully added to Firestore"); res = "Successfully executed"; } catch (firestoreError) { print("Firestore写入错误: ${firestoreError.toString()}"); res = "Firestore写入失败: ${firestoreError.toString()}"; } }
内容的提问来源于stack exchange,提问作者Vamsi Krishna Peruri

