我正在尝试实现一种功能,其中该应用程序在网格视图中显示当前用户之外的所有用户详细信息。我一直在尝试将snapshots
分配给_stream
,然后在_stream
中应用StreamBuilder()
的值。但这会引发错误。
Database _database = Database();
Stream _stream;
String currentUserId;
@override
void initState() {
getCurrentUserId(); //currentUserId gets its value here
getAllUsers();
super.initState();
}
getAllUsers() async {
Stream<QuerySnapshot> snapshots = await _database.getAllUsers();
_stream = snapshots.map((querySnapshot) => querySnapshot.documents.where((documentSnapshot)
=> documentSnapshot.data["userId"] != currentUserId
).toList())
}
//..
StreamBuilder(
stream: _stream,
builder: (context, snapshot) {
if (snapshot.data != null)
//..
}
//..
)
新功能:如果我添加as QuerySnapshot
,则snapshot
中的StreamBuilder
将为null,而不是引发异常。
// NEW
_stream = snapshots.map((querySnapshot) => querySnapshot.documents.where((documentSnapshot)
=> documentSnapshot.data["userId"] != currentUserId
).toList() as QuerySnapshot);
数据库类
getAllUsers() async {
return await _firestore.collection("users").snapshots();
}
例外
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<dynamic>(dirty, state: _StreamBuilderBaseState<dynamic, AsyncSnapshot<dynamic>>#6e31f):
Class 'List<DocumentSnapshot>' has no instance getter 'documents'.
Receiver: Instance(length:2) of '_GrowableList'
Tried calling: documents
The relevant error-causing widget was:
StreamBuilder<dynamic> file:///Users/suriantosurianto/AndroidStudioProjects/apui/lib/fragments/home_fragment.dart:66:12
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 _HomeFragmentState.build.<anonymous closure> (package:apui/fragments/home_fragment.dart:80:42)
#2 StreamBuilder.build (package:flutter/src/widgets/async.dart:509:81)
#3 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:127:48)
#4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
答案 0 :(得分:0)
我们不知道此错误指向哪一行,但是,如果我理解正确,原因可能是StreamBuilder
类的stream
属性Stream
类型({{3 }}。
似乎_stream
是使用list
方法(reference)从stream
创建的toList
。我会尝试删除此toList
方法,然后看看会发生什么。
我希望它将对您有帮助!
答案 1 :(得分:0)
// NEW
_stream = snapshots.map((querySnapshot) => querySnapshot.documents.where((documentSnapshot)
=> documentSnapshot.data["userId"] != currentUserId
).toList() as QuerySnapshot);
这里querySnapshot
是List<DocumentSnapshot>
!!!
您可能必须使用querySnapshot.where()
答案 2 :(得分:0)
正如其他人指出的那样,querySnapshot是List<DocumentSnapshot>
而不是DocumentSnapshot
,因此您不能使用getter .documents
(getter仅用于DocumentSnapshot
,不能用于对于List
),这是因为正在检索除当前用户外的每个用户的DocumentSnapshot
(每个用户的DocumentSnapshot
,因此是List<DocumentSnapshot>
)。
如果您要返回List<DocumentSnapshot>
类型的流,则
_stream = snapshots
.map<List<DocumentSnapshot>>((querySnapshot) =>
querySnapshot.where((documentSnapshot) =>
documentSnapshot.data["userId"] != currentUserId)
);