Stephan
Stephan

Reputation: 2019

How to use await instead of .then() in Dart

I'm having the following lines in a Flutter app. _devicesRef refers to some node in a Firebase Realtime Database.

_devicesRef.child(deviceId).once().then((DataSnapshot data) async {
    print(data.key);
    var a = await ...
    print(a);
}

These lines work fine. Now I want to use await instead of .then(). But somehow, once() never returns.

var data = await _devicesRef.child(deviceId).once();
print(data.key);
var a = await ...
print (a);

So print(data.key) is never called.

What's wrong here?

Upvotes: 0

Views: 1579

Answers (3)

Brian Quah
Brian Quah

Reputation: 21

If you intend to use await as a replacement of .then() in your snippet, this is how you can accomplish it:

() async {
    var data = await _devicesRef.child(deviceId).once();
    print(data.key);
    var a = await ...
    print(a);
}();

By placing the code in the asynchronous closure () async {}(), we are not preventing execution of the code that comes after, in a similar fashion to using .then().

Upvotes: 2

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76223

It could be explained by the code following your snippet. Perhaps the future completion is trigger by something after your code and transforming your code with await will wait until a completion that never happens.

For instance, the following code works:

main() async {
  final c = Completer<String>();
  final future = c.future;
  future.then((message) => print(message));
  c.complete('hello');
}

but not this async/await version:

main() async {
  final c = Completer<String>();
  final future = c.future;
  final message = await future;
  print(message);
  c.complete('hello');
}

Upvotes: 3

parth jansari
parth jansari

Reputation: 178

it should be encased in an async function like this to use await

Furtre<T> myFunction() async {
  var data = await _devicesRef.child(deviceId).once();
  return data;
}

Upvotes: 0

Related Questions