1

I have a problem. It is getting data from firebase realtime database. If data is added it throws an error.

_TypeError (type 'String' is not a subtype of type 'int' of 'index')

According to the image below that has been flattened enter image description here

realtime databse Json in my code patient_ID is "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"
      },      
    }
  }
}

realtime database

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(),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  },
)
Nutdanai
  • 33
  • 3
  • It looks like the data at `notification/$patient_ID` in your database, is not what the code expects it to be. Can you edit your question to show this data (as JSON text, no screenshots please)? You can get this by clicking the "Export JSON" link in the overflow menu (⠇) on your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen May 24 '23 at 13:59
  • I have added the json data to my post for you. Is it the one you want? – Nutdanai May 24 '23 at 14:25

1 Answers1

0

Your code reads this JSON data:

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

Which you then parse with:

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

So the keys in your data map are strings ("calling", "is_read", etc), not numbers.

You try to access values in data by a numeric index here:

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

This isn't possible (as they are string values), so the runtime throws an error indicating this mistake.


If you want to show the individual properties in a list view, you can use values to get a list of the values in the map, and then use elementAt to access the map items by index. Something like:

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

Also see: How to access map keys through index? Dart

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I tried changing to ` final itemDataNoti = dataNotification.elementAt(index); ` But it's still the same. – Nutdanai May 24 '23 at 14:52
  • "it's still the same" is hard to help with. It also seems unlikely that you'd get the exact same error message after the code change. Please be specific and detailed. Also note that the code in my answer is `dataNotification.values.elementAt(index)`, which is not the same what you shared. – Frank van Puffelen May 24 '23 at 15:30