1

我正在尝试从 Firebase Friestore 读取最后一个条目,如下所示:

这是我的流:

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

这是我的流生成器​​:

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');
                }),

我收到以下错误:

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

有谁知道可能是什么问题?

请帮忙 :)

4

2 回答 2

1

你可以这样使用

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');
})
于 2022-01-08T17:27:47.880 回答
0

你需要使用

snapshot.data!.data()

获取文档流的数据,以便您的代码可以是

final _lastEmotion = lastEmotionSnapshot.data!.data()['emotion'];
于 2022-01-08T11:50:48.090 回答