3
votes

I am trying to understand the usage of async and await in Dart. Somehow I am having issues returning values in certain methods.

Consider the code below

Future<int> getMrn() async {
  var mrnRef = await firebaseClient.child('mrn');

  DataSnapshot ss;
  StreamSubscription<Event> onValueSubscription = await mrnRef.onValue
      .listen((event) {
    ss = event.snapshot;

    return ss.val();
  });

  //return Future<int> ss.val();
}

mrn is of type int which should be returned by getMrn method. However each time the returned ss.val() returns null. It seems that ss = event.snapshot is not seen in the last returned value

What is the correct way of doing this. Thanks

1

1 Answers

7
votes

In the code above, you're declaring anonymous function (event){..} as a callback, and your return statement relates to it, while your intention was to return from getMrn().

What are you actually need, is to complete a Future you're returning from getMrn() inside your callback.

Like this:

Future<int> getMrn() async {
  var mrnRef = await firebaseClient.child('mrn');

  Completer<int> c = new Completer<int>();
  StreamSubscription<Event> onValueSubscription = await mrnRef.onValue
      .listen((event) {
    DataSnapshot ss = event.snapshot;
    c.complete(ss.val());
  });

  return c.future;
}

but that code wouldn't work good if there second event appear in mrnRef.onValue stream. So, assuming mrnRef.onValue is a Stream, and you need only first event, it would be better to rewrite it this way:

Future<int> getMrn() async {
  var mrnRef = await firebaseClient.child('mrn');

  Event event = await mrnRef.onValue.first;
  DataSnapshot ss = event.snapshot;
  // note, you're implicitly returning a Future<int> here,
  // because our function is asyncronous
  return ss.val();
}