Flutter报错:Class 'QuerySnapshot'无'document'实例方法求助
解决
QuerySnapshot没有document方法的错误 这个错误很常见,是因为你混淆了**集合查询快照(QuerySnapshot)和单个文档快照(DocumentSnapshot)**的用法,我来帮你理清并修复:
错误原因分析
你当前的stream是监听整个users集合的变化,返回的是Stream<QuerySnapshot>——也就是整个集合所有文档的快照集合,它本身并没有document()方法(这个方法是用来获取单个文档引用的,属于CollectionReference)。你想直接用它来获取指定ID的文档,自然会触发这个错误。
解决方案(两种场景)
场景1:只需要监听单个指定ID的文档(推荐)
如果你的需求只是获取_myMobile对应的用户文档,完全不需要监听整个集合,直接监听单个文档的快照更高效:
body: StreamBuilder( // 直接监听单个文档的快照 stream: Firestore.instance.collection('users').document(_myMobile).snapshots(), builder: (context, snapshot){ if(!snapshot.hasData) return Text('Loading data.....'); // 此时snapshot.data是DocumentSnapshot,可以直接取数据 // 建议判断文档是否存在,避免空数据报错 if (!snapshot.data.exists) { return Text('User not found'); } return Center(child: Text(snapshot.data.data["Name"]),); } )
场景2:必须监听整个集合,从中筛选指定文档
如果你因为业务需要必须监听整个集合的变化,然后从中找到_myMobile对应的文档,可以通过QuerySnapshot的documents列表来筛选:
body: StreamBuilder( stream: Firestore.instance.collection('users').snapshots(), builder: (context, snapshot){ if(!snapshot.hasData) return Text('Loading data.....'); // 从documents列表中找到指定ID的文档 final targetDoc = snapshot.data.documents.firstWhere( (doc) => doc.documentID == _myMobile, // 设置默认值,避免找不到文档时报错 orElse: () => null, ); if (targetDoc == null) { return Text('User not found'); } return Center(child: Text(targetDoc.data["Name"]),); } )
额外提示
如果你使用的是较新版本的Cloud Firestore SDK(比如cloud_firestore: ^2.0.0+),API有一些变更,比如document()改为doc(),documents改为docs,documentID改为id。如果是新版本,场景1的代码需要调整为:
body: StreamBuilder( stream: FirebaseFirestore.instance.collection('users').doc(_myMobile).snapshots(), builder: (context, snapshot){ if(snapshot.connectionState == ConnectionState.waiting) return Text('Loading data.....'); if (!snapshot.hasData || !snapshot.data!.exists) { return Text('User not found'); } return Center(child: Text(snapshot.data!.data()!["Name"]),); } )
内容的提问来源于stack exchange,提问作者Navneet Kumar
相关产品推荐
相关产品推荐

