Reputation: 42426
I have below code in flutter
:
getData() {
final linksStream = getLinksStream().listen((String uri) async {
return uri;
});
}
In getData
method, I want to return the value of uri
which is from a stream listener. Since this value is generated at a later time, I am thinking to response a Future object in getData
method. But I don't know how I can pass the uri
as the value of Future
.
In javascript
, I can simply create a promise
and resolve
the value uri
. How can I achieve it in dart
?
Upvotes: 3
Views: 2890
Reputation: 435
In your code 'return uri' is not returning from getData but returning from anonymous function which is parameter of listen. Correct code is like:
Future<String> getData() {
final Completer<String> c = new Completer<String>();
final linksStream = getLinksStream().listen((String uri) {
c.complete(uri);
});
return c.future;
}
Upvotes: 6
Reputation: 12673
Try this
Future<String> getData() async{
final linksStream = await getLinksStream().toList();
return linksStream[0].toString();
}
Upvotes: 0