我有个问题从firebase实时数据库获取数据。如果添加数据,则会抛出错误。
_TypeError(类型“String”不是“index”的类型“int”的子类型)
根据下面的图像,已被展平
我的代码patient_ID中的实时数据库Json为“1264758392012”
{
"notification": {
"1264758392012": {
"-NWD2baVxumoarhIVQS6": {
"calling_by": "Nurse",
"is_read": true,
"misscall": true,
"timestamp": "2023-05-24 20:59:11.535176"
},
"-NWD2rEc8eGGaOF72fCF": {
"calling_by": "Nurse",
"is_read": false,
"misscall": true,
"timestamp": "2023-05-24 21:00:15.649757"
},
"-NWD3tqlVO5TDmOuHOoR": {
"calling_by": "Nurse",
"is_read": false,
"misscall": true,
"timestamp": "2023-05-24 21:04:48.450108"
},
}
}
}
实时数据库
void realtime()async {
final ref = await FirebaseDatabase.instance.ref();
ref.child('notification/$patient_ID').onValue.listen((event) {
final snapshot = event.snapshot;
if (snapshot.exists) {
setState(() {
// dataNotification.clear();
data = snapshot.value as Map<dynamic, dynamic>;
});
setState(() {
dataNotification.clear();
dataNotification.addAll(data.values);
});
print("dataNoti: $dataNotification");
} else {
print('No data available.');
}
});
}
Listview.builder
ListView.builder(
key: UniqueKey(),
physics: NeverScrollableScrollPhysics(),
padding: EdgeInsets.zero,
shrinkWrap: true,
itemCount: dataNotification.length,
itemBuilder: (BuildContext context,int index) {
final itemDataNoti = dataNotification[index];
return Container(
height: 80,
width: double.infinity,
child: Card(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const 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: [
itemDataNoti == null ?Text("data") :Text(
"calling by: ${itemDataNoti["calling_by"].toString()}",
style: GoogleFonts.notoSansThai(),
),
],
),
),
],
),
),
),
);
},
)
1条答案
按热度按时间llmtgqce1#
你的代码读取这个JSON数据:
然后用以下命令解析:
因此,
data
Map中的键是字符串("calling"
,“is_read"
等),而不是数字。您可以尝试通过以下数字索引访问
data
中的值:这是不可能的(因为它们是字符串值),所以运行时抛出一个错误来指示这个错误。
如果要在列表视图中显示各个属性,可以使用use
values
获取Map中的值列表,然后使用useelementAt
按索引访问Map项。类似于:参见:How to access map keys through index? Dart