Flutter登录导航失败:_Map转Map<String,String>类型转换异常
解决Flutter Firebase登录后页面不跳转及Map类型转换异常问题
核心问题在于Firestore返回的是Map<String, dynamic>类型数据,你强行将其转为Map<String, String>导致类型转换异常,中断了后续的导航逻辑。以下是具体修复方案:
1. 修正Firestore数据读取的类型转换逻辑
不要直接强制类型转换,先接收dynamic类型的Map,再安全转换每个值为String:
// 读取Firestore文档数据 final doc = await FirebaseFirestore.instance .collection('user_answers') .doc(currentUserUid) .get(); if (doc.exists) { // 先获取原生的dynamic类型Map Map<String, dynamic> rawAnswers = doc.data() as Map<String, dynamic>; // 安全转换为Map<String, String>,处理空值或非String类型 Map<String, String> userAnswers = rawAnswers.map( (key, value) => MapEntry(key, value?.toString() ?? ''), ); // 这里执行你的导航逻辑 if (userAnswers['key'] == 'target_value') { Navigator.pushReplacementNamed(context, '/target_page'); } else { Navigator.pushReplacementNamed(context, '/default_page'); } } else { // 用户无答题记录,跳转到答题页面 Navigator.pushReplacementNamed(context, '/treatmentReady'); }
如果部分字段是数字、布尔等特定类型,单独处理更稳妥,比如:
int score = rawAnswers['score'] as int; bool isCompleted = rawAnswers['completed'] as bool;
2. 用异常捕获保障导航逻辑执行
给数据读取和转换逻辑加上try-catch,避免异常导致导航代码完全不执行:
try { final doc = await FirebaseFirestore.instance .collection('user_answers') .doc(currentUserUid) .get(); if (doc.exists) { // 类型转换和导航逻辑 } else { Navigator.pushReplacementNamed(context, '/treatmentReady'); } } catch (e) { print('处理用户答案时出错: $e'); // 异常兜底,跳转到默认页面或重新答题页 Navigator.pushReplacementNamed(context, '/treatmentReady'); }
3. 统一Firestore存入的数据类型
回到TreatmentReadyScreen的存数据代码,确保存入的字段值类型统一,避免后续读取时类型混乱:
await FirebaseFirestore.instance .collection('user_answers') .doc(userUid) .set({ 'question1': userAnswer1.toString(), // 统一转为String存入 'question2': userAnswer2.toString(), // 其他字段同理 });
内容的提问来源于stack exchange,提问作者asme sahouli
相关产品推荐
相关产品推荐

