Flutter中的Firebase实时数据库和Listview生成器

83qze16e  于 2023-05-30  发布在  Flutter
关注(0)|答案(1)|浏览(203)

我有个问题从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(),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  },
)
llmtgqce

llmtgqce1#

你的代码读取这个JSON数据:

{
  "calling_by": "Nurse",
  "is_read": true,
  "misscall": true,
  "timestamp": "2023-05-24 20:59:11.535176"
}

然后用以下命令解析:

data = snapshot.value as Map<dynamic, dynamic>;

因此,dataMap中的键是字符串("calling",“is_read"等),而不是数字。
您可以尝试通过以下数字索引访问data中的值:

itemBuilder: (BuildContext context,int index) {
  final itemDataNoti = dataNotification[index];
  ...

这是不可能的(因为它们是字符串值),所以运行时抛出一个错误来指示这个错误。
如果要在列表视图中显示各个属性,可以使用use values获取Map中的值列表,然后使用use elementAt按索引访问Map项。类似于:

itemBuilder: (BuildContext context,int index) {
  final itemDataNoti = dataNotification.values.elementAt(index);
  // Now you can access the key and value of itemDataNoti
  ...

参见:How to access map keys through index? Dart

相关问题