Flutter: retrieve log history from real time database

Viewed 145

UPDATE

i want to retrieve user log history in realtime from path Staff=>randomID1=>log=> randomID2 i want to display the the data from randomID2 in showDialog.

my path : final databaseRef = FirebaseDatabase.instance.reference().child('Staff');

       child: FirebaseAnimatedList(
          query: dataRef,
          itemBuilder: (BuildContext context, DataSnapshot snapshot,
              Animation<double> animation, int index) {

            var log = snapshot.value['log'];
            var dates = log.keys.toList();
            var key = dates[index];

            return Card(
              child: ListTile(
                title: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text('Email             :  ${snapshot.value['email']}'),
                    Text(
                        'Mail Status   :  ${snapshot.value['mail-status'].toString()}'),
                    Text('Date               :  ${snapshot.value['date']}'),
                    Text('Time              :  ${snapshot.value['time']}'),

                    Text(snapshot.value['log'][key]['current-date']),
                    Card(
                      child: ListTile(
                        subtitle: Column(
                          children: <Widget>[
                            for(var i = 0; i<log.length; i++)...[
                              Text(snapshot.value['log'][key]['current-date'])
                            ],       
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          })),

my realtime database

my error:

Exception has occurred. NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: []("current-date"))

i dont know why it display the same key value enter image description here

1 Answers

The problem comes from this line:

Text(snapshot.value['log'][index]['current-date'])

The index is going to be a sequential numeric value (0, 1, 2, 3, etc), while the keys in the JSON you show are formatted dates. So snapshot.value['log'][index] doesn't exist in the JSON and gives back null, which explains the error message you get.


To get the key at an index in the JSON, you can do:

var log = snapshot.value['log']
var dates = log.keys.toList();
var key = dates[index];

Note: you may need to cast or convert some of the types in this snippet. If you get errors of that type, please try to resolve them by searching for the error message before commenting.

And then you can use that key in:

Text(snapshot.value['log'][key]['current-date'])
Related