0

我正在为我的数据库工作使用/学习 Firebase。我的快照就像 _jsonQuerySnapshot 或 _jsonDocumentSnapshot 一样。但它必须是 QuerySnapshot 或 DocumentSnapshot。因此,我必须对我的快照进行编码和解码以使用我的数据。如果我不使用 encode decode json 我总是会收到 null 或 object 错误。这是我的课程从状态扩展


class _MyHomePageState extends State<MyHomePage> {
  final _firestore = FirebaseFirestore.instance;


  @override
  Widget build(BuildContext context) {
    CollectionReference moviesRef=_firestore.collection('movies');
    DocumentReference babaRef = _firestore.collection('movies').doc('Baba');



    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        title: Text('FireStore Crud'),
      ),
      body: Center(
        child: Container(
          child: Column(
            children: [
              StreamBuilder<QuerySnapshot>(
                stream: moviesRef.snapshots(),
                builder: (BuildContext context,AsyncSnapshot asyncSnapshot){
                  List<DocumentSnapshot>listOfDocumentSnapshot=asyncSnapshot.data.docs;
                  return Flexible(
                    child: ListView.builder(
                      itemCount: listOfDocumentSnapshot.length,
                      itemBuilder: (context,index){
                        Text('${listOfDocumentSnapshot[index].data()['name']}' ,style: TextStyle(fontSize: 24),);
                      },
                    ),
                  );



                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这是我的错误。

在此处输入图像描述

4

1 回答 1

2

首先,检查您的数据是否为空,然后[]在其上使用。可能,listOfDocumentSnapshot[index].data()为空。如果为 null,则渲染另一个 UI,例如加载屏幕。也就是说,您的加载屏幕必须显示,直到到达数据。

例如:

builder: (BuildContext context,AsyncSnapshot asyncSnapshot){
   List<DocumentSnapshot>? listOfDocumentSnapshot = asyncSnapshot.data.docs;

   if(!listOfDocumentSnapshot.hasData || listOfDocumentSnapshot == null){
      return LoadingScreen(); //etc.
   }

   return Flexible(
      child: ListView.builder(
         itemCount: listOfDocumentSnapshot.length,
         itemBuilder: (context,index){
            Text('${listOfDocumentSnapshot[index].data()['name']}' ,style: TextStyle(fontSize: 24),);
         },
      ),
   );
},

Futures(异步程序)需要一些时间来获取数据,你必须让你的 UI 等到你获取数据。例如数据库连接,从某处读/写某些东西等。

有关更多详细信息,您可以阅读这篇文章

于 2021-12-23T15:31:12.840 回答