问题描述
我有一个 Flutter 应用,它使用 Firebase-storage 和 google-signin.我正在尝试执行的步骤非常简单:
I have a Flutter app which uses Firebase-storage and google-signin.the steps I am trying to do is so simple:
1- 使用 Google 登录(完成).
1- Sign-in using Google (Done).
2- 获取当前用户 ID(完成).
2- Get Current User Id (Done).
3- 在为流构建器构建流时使用用户 ID(问题).
3- Use the User Id when construct the stream for the stream builder (the problem).
到目前为止我所做的是使用 Future
来获取当前用户 ID,然后将用户 ID 注入 Where 子句
what I did so far is that I am using a Future
to get the Current User Id,then to inject the user Id inside the Where clause
.where('userId', isEqualTo: userId)
这就是我的结局:
这是我应该创建流的部分:
this is the part where I should create the stream:
// Get document's snapshots and return it as stream.
Future<Stream> getDataStreamSnapshots() async {
// Get current user.
final User user = await FirebaseAuth().currentUser();
String userId = user.uid;
Stream<QuerySnapshot> snapshots =
db
.collection(db)
.where("uid", isEqualTo: userId)
.snapshots();
try {
return snapshots;
} catch(e) {
print(e);
return null;
}
}
这是我应该在哪里调用和接收流的部分,
and this is the part where should I call and receive the stream,
...
children: <Widget>[
StreamBuilder<QuerySnapshot>(
stream: CALLING THE PREVIOUS FUNCTION,
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
...
}
...
但是这段代码不起作用,因为我无法获得 Future 应该返回的值?有什么想法吗?
But this code does not work, because I am not able to get the value that should returned by the Future? any idea?
非常感谢
推荐答案
你永远不应该有 Future
,那是双异步,这是不必要的.只需返回一个 Stream
,然后在准备好之前不必发出任何事件.
You should never have a Future<Stream>
, that's double-asynchrony, which is unnecessary. Just return a Stream
, and then you don't have to emit any events until you are ready to.
不清楚 try
/catch
正在保护什么,因为非 Future
的返回不能抛出.如果您返回一个流,只需在该流上发出任何错误即可.
It's not clear what the try
/catch
is guarding because a return of a non-Future
cannot throw. If you return a stream, just emit any error on the stream as well.
您可以将代码重写为:
Stream<QuerySnapshot> getDataStreamSnapshots() async* {
// Get current user.
final User user = await FirebaseAuth().currentUser();
String userId = user.uid;
yield* db
.collection(db)
.where("uid", isEqualTo: userId)
.snapshots();
}
async*
函数是异步的,因此您可以使用 await
.它返回一个 Stream
,您可以使用 yield event;
或 yield* streamOfEvents;
在流上发出事件.
An async*
function is asynchronous, so you can use await
. It returns a Stream
, and you emit events on the stream using yield event;
or yield* streamOfEvents;
.
这篇关于如何在 Flutter 中基于 Future 结果构建 Stream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!