1

I am trying to read last entry from Firebase Friestore like this:

This is my stream:

final getLastEmotion = _emotionsDbReference
    .orderBy('timeStamp', descending: true)
    .limit(1)
    .snapshots();

and this is my stream builder:

StreamBuilder(
                stream: getLastEmotion,
                builder: (BuildContext context,
                    AsyncSnapshot lastEmotionSnapshot) {
                  if (lastEmotionSnapshot.data == null)
                    return CircularProgressIndicator();

                  if (lastEmotionSnapshot.hasError) {
                    return new Text(
                        'Error in receiving snapshot: ${lastEmotionSnapshot.error}');
                  }
                  if (!lastEmotionSnapshot.hasData) {
                    return Center(
                      child: CircularProgressIndicator(
                        backgroundColor: Theme.of(context).primaryColor,
                      ),
                    );
                  }

                  final _lastEmotion = lastEmotionSnapshot.data!['emotion'];

                  return Text('Last emotion: $_lastEmotion');
                }),

I am receiving the following error:

Class '_JsonQuerySnapshot' has no instance method '[]'.
Receiver: Instance of '_JsonQuerySnapshot'
Tried calling: []("emotion")

Does anyone know what might be a problem?

Please help :)

AturicLiqr
  • 49
  • 7

2 Answers2

1

You can use like this

StreamBuilder(
stream: getLastEmotion,
builder: (BuildContext context, AsyncSnapshot lastEmotionSnapshot) {
  if (lastEmotionSnapshot.data == null) {
    return const CircularProgressIndicator();
  }

  if (lastEmotionSnapshot.hasError) {
    return Text(
        'Error in receiving snapshot: ${lastEmotionSnapshot.error}');
  }
  if (!lastEmotionSnapshot.hasData) {
    return Center(
      child: CircularProgressIndicator(
        backgroundColor: Theme.of(context).primaryColor,
      ),
    );
  }

  final _lastEmotion = lastEmotionSnapshot.data!.docs[0]['emotion'];


  return Text('Last emotion: $_lastEmotion');
})
Khadga shrestha
  • 1,120
  • 6
  • 11
0

You need to use

snapshot.data!.data()

to get the data of the document stream so your code could be

final _lastEmotion = lastEmotionSnapshot.data!.data()['emotion'];
Khadga shrestha
  • 1,120
  • 6
  • 11
  • Unfortunately, this doesn't work neither. This time I get: `Class '_JsonQuerySnapshot' has no instance method 'data'. Receiver: Instance of '_JsonQuerySnapshot' Tried calling: data()` – AturicLiqr Jan 08 '22 at 17:05
  • Oh got it here you are quering the data which will return in array format so you have to specify array element. – Khadga shrestha Jan 08 '22 at 17:12