returning a value in sync and await in dart -
i trying understand usage of async , await in dart. somehow having issues returning values in methods.
consider 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 of type int should returned getmrn method. each time returned ss.val() returns null. seems ss = event.snapshot not seen in last returned value
what correct way of doing this. thanks
in code above, you're declaring anonymous function (event){..} callback, , return statement relates it, while intention return getmrn().
what need, complete future you're returning getmrn() inside 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 code wouldn't work if there second event appear in mrnref.onvalue stream. so, assuming mrnref.onvalue stream, , need first event, better rewrite 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 future<int> here, // because our function asyncronous return ss.val(); }
Comments
Post a Comment