Flutter中Firebase实时数据库与ListView Builder报错问题咨询
问题排查与解决:Flutter Firebase Realtime Database 类型错误
错误原因
报错_TypeError (type 'String' is not a subtype of type 'int' of 'index')的核心原因是**dataNotification类型不匹配**:
ListView.builder通过整数索引index访问数据,要求dataNotification是List类型;- 若
dataNotification被声明为Map,或数据添加时未将Firebase返回的Map值转为List,就会出现用整数索引访问字符串键Map的类型兼容错误。
解决方案
1. 修正dataNotification类型声明
在State类中明确将其声明为List类型:
List<Map<dynamic, dynamic>> dataNotification = [];
2. 修正数据获取逻辑
修改realtime()方法,将Firebase返回的Map值转为List后赋值:
void realtime() { FirebaseDatabase.instance.ref().child('notification/$patient_ID').onValue.listen((event) { final snapshot = event.snapshot; if (snapshot.exists) { setState(() { final data = snapshot.value as Map<dynamic, dynamic>; // 将Map的values转为List并强转类型 dataNotification = data.values.toList().cast<Map<dynamic, dynamic>>(); }); print("dataNoti: $dataNotification"); } else { print('No data available.'); setState(() { dataNotification.clear(); }); } }); }
注:移除了不必要的
async/await,ref()方法无需异步调用。
3. 优化ListView空值判断(可选)
增加严谨判空避免空指针异常:
ListView.builder( key: UniqueKey(), physics: const NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, shrinkWrap: true, itemCount: dataNotification.length, itemBuilder: (BuildContext context, int index) { final itemDataNoti = dataNotification[index]; if (itemDataNoti == null) { return const SizedBox(height: 80, child: Center(child: Text("无数据"))); } return Container( height: 80, width: double.infinity, child: Card( child: Padding( padding: const EdgeInsets.all(10.0), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.only(left: 10), child: Icon( Icons.phone_missed, color: Colors.red, ), ), Padding( padding: const EdgeInsets.only(left: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "calling by: ${itemDataNoti["calling_by"] ?? 'Unknown'}", style: GoogleFonts.notoSansThai(), ), ], ), ), ], ), ), ), ); }, )
验证逻辑
修改后,dataNotification将存储每个通知节点的Map数据列表,ListView通过整数索引访问时类型匹配,新增数据时不会再抛出类型错误。
内容的提问来源于stack exchange,提问作者Nutdanai
相关产品推荐
相关产品推荐

