Flutter中使用.toString()仍报“int不是String子集”错误求助
解决Firestore数据转换报错:
type 'int' is not a subset of type 'String' 针对你遇到的问题——即使使用.toString()仍抛出类型不匹配异常,可尝试以下几种处理方式:
1. 增加空安全检查与兜底值
直接在转换时处理字段可能为空的情况,避免因字段不存在或为null触发异常:
Text( document['Money']?.toString() ?? '0', // 字段为空时显示兜底值0 style: Theme.of(context).textTheme.displaySmall, )
2. 显式类型转换后再处理
先将Firestore取出的值显式转为可空int类型,再做字符串转换,确保类型安全:
Widget buildItem(BuildContext context, DocumentSnapshot document) { // 显式转换Money字段为可空int final int? money = document['Money'] as int?; return ListTile( title: Row( children: [ Expanded( child: Text( document['Name'] as String, // 建议对Name字段也做显式类型转换,避免潜在问题 style: Theme.of(context).textTheme.headline1, ), ), Container( decoration: const BoxDecoration( color: kBlueLight, ), padding: const EdgeInsets.all(10), child: Text( money?.toString() ?? '0', style: Theme.of(context).textTheme.displaySmall, ), ) ], ), ); }
3. 校验Firestore数据一致性
确认所有测试文档中的Money字段均为整数类型,避免部分文档该字段是字符串或其他类型,导致批量处理时出现类型不匹配。
内容的提问来源于stack exchange,提问作者FrostByte
相关产品推荐
相关产品推荐

