Firebase报错:'Future<dynamic>'不是'String'子类型问题求助
问题解决:'Future' is not a subtype of type 'String' 错误
核心原因
getUserId()是异步函数(带async关键字),你调用时没加await,直接把Future对象赋值给了String类型的userId,导致类型不匹配触发错误。
修复步骤
1. 修正异步函数调用与返回类型
给getUserId()指定明确返回类型,调用时必须加await,同时处理用户未登录的空值情况:
// 给getUserId()指定返回类型,未登录时返回null Future<String?> getUserId() async { User? user = FirebaseAuth.instance.currentUser; if (user != null) { return user.uid; } else { print('No user signed in.'); return null; } } // 在addUserScores中调用时加await,并判断userId是否为空 Future<String> addUserScores({ required int score, required String gameCategory, required String gameName, }) async { try { String? userId = await getUserId(); if (userId == null) { print("用户未登录,无法存储分数"); return 'failed: user not logged in'; } // 后续数据库操作代码不变... } on Exception catch (e) { print(e); return 'failed: ${e.toString()}'; } return 'success'; }
2. 额外优化:避免空指针异常
原代码中直接用totalRoundData.data()!会在文档不存在时触发空指针,建议先判断文档是否存在:
var totalRoundData = await gameCollectionRef.get(); int totalRoundsPlayed; if (!totalRoundData.exists) { // 文档不存在时初始化totalRoundsPlayed为0 await gameCollectionRef.set({'totalRoundsPlayed': 0}); totalRoundsPlayed = 0; } else { totalRoundsPlayed = totalRoundData.data()?['totalRoundsPlayed'] ?? 0; }
修复后的完整代码
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class ScoreMethods { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final FirebaseAuth _auth = FirebaseAuth.instance; Future<String?> getUserId() async { User? user = FirebaseAuth.instance.currentUser; if (user != null) { return user.uid; } else { print('No user signed in.'); return null; } } Future<String> addUserScores({ required int score, required String gameCategory, required String gameName, }) async { try { String? userId = await getUserId(); if (userId == null) { print("用户未登录,无法存储分数"); return 'failed: user not logged in'; } var userRef = _firestore.collection('users').doc(userId); var gameCategoryDoc = userRef.collection('gameScore').doc('category'); var gameDoc = gameCategoryDoc.collection(gameCategory).doc(gameName); var totalRoundData = await gameDoc.get(); int totalRoundsPlayed; if (!totalRoundData.exists) { await gameDoc.set({'totalRoundsPlayed': 0}); totalRoundsPlayed = 0; } else { totalRoundsPlayed = totalRoundData.data()?['totalRoundsPlayed'] ?? 0; } var roundNumber = 'round_${totalRoundsPlayed + 1}'; await gameDoc.collection('rounds').doc(roundNumber).set({'score': score}); await gameDoc.update({ 'totalRoundsPlayed': totalRoundsPlayed + 1, }); print("数据添加成功"); return 'success'; } on Exception catch (e) { print("存储失败: $e"); return 'failed: ${e.toString()}'; } } }
内容的提问来源于stack exchange,提问作者Tahmeed Zamindar
相关产品推荐
相关产品推荐

