Flutter Android应用Timeline页面出现类型不匹配错误求助
解决"type int is not a subtype of type String"错误
这个错误本质是数据类型不匹配,发生在将Firestore文档转换为Post对象的过程中——某个字段在Firestore里存储的是int类型,但你的Post模型里对应的字段定义成了String(反之亦然)。结合你的代码,我来帮你一步步排查修复:
1. 定位错误核心
错误肯定出在Post.fromDocument(doc)这个转换方法里。当你从Firestore获取timelinePosts文档后,调用这个方法把文档映射为Post实例时,某个字段的类型和模型定义不一致,导致类型转换失败。
2. 排查关键步骤
第一步:检查Firestore数据库字段类型
打开Firebase控制台,找到timelinePosts集合,查看任意一个文档的字段:
- 重点看数字类字段:比如
timestamp、likes、commentsCount这类字段,确认它们在Firestore里的类型是int还是String。 - 比如如果
timestamp是Firestore的Timestamp类型,或者你存的是时间戳整数(millisecondsSinceEpoch),那你的Post模型里对应的字段类型就不能是String。
第二步:检查Post类的fromDocument方法
找到你的Post模型文件,查看fromDocument构造函数的字段赋值:
举几个常见的错误示例:
错误:Firestore里
likes是int,但模型里定义为String// 错误写法 class Post { String likes; Post.fromDocument(DocumentSnapshot doc) { likes = doc['likes']; // 这里直接把int赋值给String,就会报错 } }修复:要么把模型里的
likes改成int,要么转换为字符串:likes = doc['likes'].toString();错误:Firestore里
timestamp是Timestamp类型,但模型里定义为String// 错误写法 String timestamp; Post.fromDocument(DocumentSnapshot doc) { timestamp = doc['timestamp']; // Timestamp不能直接赋值给String }修复:转换为整数或者字符串:
// 转成时间戳整数 int timestamp = doc['timestamp'].millisecondsSinceEpoch; // 或者转成可读字符串 String timestamp = doc['timestamp'].toDate().toString();
3. 额外的代码问题提醒
你的Timeline组件里还有一个潜在问题:getFollowing方法里使用了currentUser.id,但你的state类里并没有currentUser变量,应该用widget.currentUser.id,否则会报空指针错误:
// 错误写法 await followingRef.document(currentUser.id)... // 修复后 await followingRef.document(widget.currentUser.id)...
按照这个思路排查,应该能快速定位到类型不匹配的字段,解决这个错误。
内容的提问来源于stack exchange,提问作者Waseem Khan
相关产品推荐
相关产品推荐

