Flutter报错:'String'不是'index'的'int'子类型,求解决
问题排查:type 'String' is not a subtype of type 'int' of 'index'
错误根源
你的User模型类中,fromSnap方法对stars字段的默认值赋值错误,导致类型不匹配:
原代码中:
stars: snapshot['stars'] ?? '',
当Firestore中snapshot['stars']不存在时,你给了一个空字符串'',但User类定义的stars是List类型,这就导致stars字段实际被赋值为String类型。后续代码尝试将其当作List使用(比如索引访问、遍历)时,就会触发类型转换错误。
修复方案
修改User模型的fromSnap方法,将stars的默认值改为空列表[]:
static User fromSnap(DocumentSnapshot snap) { var snapshot = snap.data() != null ? snap.data() as Map<String, dynamic> : {}; return User( stars: snapshot['stars'] ?? [], // 替换原有的''为[] email: snapshot['email'] ?? '', uid: snapshot['uid'] ?? '0000000', profileUrl: snapshot['profileUrl'] ?? '', username: snapshot['username'] ?? '', bio: snapshot['bio'] ?? '', followers: snapshot['followers'] ?? [], following: snapshot['following'] ?? [], ); }
额外优化建议
为避免动态类型带来的潜在问题,建议给User类中的列表字段添加具体类型注解,示例如下:
final List<String> stars; final List<String> followers; final List<String> following;
同时确保构造函数和fromSnap方法中的赋值类型一致,增强代码的类型安全性。
内容的提问来源于stack exchange,提问作者Eain Hmun Khin
相关产品推荐
相关产品推荐

