首页 > 解决方案 > 颤动:在 null 上调用的 getter 文档会显示一段时间

问题描述

我正在从无状态小部件调用方法。本文档从 firebase 数据库查询。但是当它在输出中显示错误一段时间然后显示结果时。我怎样才能停止那 3 秒的错误。这是显示的错误

吸气剂“文档”在 null 上被调用。

这是我的代码。

class chats extends StatelessWidget { 
@override
  Widget build(BuildContext context) {
child: Container(child:getlast())
}}

这就是肉食

getlast(){
    var groupChatId = 123456789;
    var id = chat.UID;
      return FutureBuilder (
        future: Firestore.instance
            .collection("messages")
            .document(groupChatId)
            .collection(groupChatId)
            .orderBy("timestamp", descending: true)
            .limit(1)
            .getDocuments(),
        builder: (context,AsyncSnapshot snapshot) {
          var con = snapshot.data.documents[0].data["content"];
         Container(
                  height: 27,
                  child: Text("You: $con",
                      overflow: TextOverflow.fade,
                      style:  TextStyle(
                        fontSize: 20),
                   )});
            }

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


使用时,FutureBuilder您需要检查connectionState

          FutureBuilder(
            future: Firestore.instance
            .collection("messages")
            .document(groupChatId)
            .collection(groupChatId)
            .orderBy("timestamp", descending: true)
            .limit(1)
            .getDocuments(),
            builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                var con = snapshot.data.documents[0].data["content"];
              Container(
                  height: 27,
                  child: Text("You: $con",
                      overflow: TextOverflow.fade,
                      style:  TextStyle(
                        fontSize: 20),
                   )});
              } else if (snapshot.connectionState == ConnectionState.none) {
                return Text("No data");
              }
              return CircularProgressIndicator();
            },
          ),

documents在 null 上调用,表示数据仍未检索,因此通过使用connectionState.done您可以确保检索到数据。

https://api.flutter.dev/flutter/widgets/ConnectionState-class.html


推荐阅读