It's probably just me but asynchronous programming in flutter seems to be an absolute nightmare. Something really simple in javascript/typescript just seems to become unnecessarily hard. for example, I'm trying to make a simple function that checks if a user is authenticated:
Future<bool> isLoggedIn() async {
var user = await FirebaseAuth.instance.currentUser();
return user == null ? false : true;
}
and then use this function in a scenario like this:
Widget _buildChild() async {
var auth = await user.isLoggedIn();
if (auth) {
return new Navigation();
} else {
return new LoginUI();
}
}
But then the second function also needs to return a future?
Functions marked 'async' must have a return type assignable to 'Future'.
using then() instead of await doesn't work either. I've run into this issue several times before when using asynchronous programming in a synchronous context. maybe it's just the that it looks and feels very similar to Promises that I'm totally missing it's functionality from the docs.
synchronous operation: A synchronous operation blocks other operations from executing until it completes. synchronous function: A synchronous function only performs synchronous operations. asynchronous operation: Once initiated, an asynchronous operation allows other operations to execute before it completes.
Dart and Flutter has great support for Asynchronous Operations .
Dart uses Future objects to represent asynchronous operations.
Exploring Asynchronous Programming In Dart & Flutter. Asynchronous programming is a type of equal programming that permits a unit of work to run independently from the essential application thread. At the point when the work is finished, it tells the main thread.
You can change your code this way:
Widget _buildChild() {
return FutureBuilder(builder: (context, AsyncSnapshot<bool> snapshot) {
if (snapshot.hasData)
return snapshot.data ? Navigation() : LoginUI();
else
return Container();
},
future: user.isLoggedIn(),);
}
It returns widget synchronously. If there is no data yet - it returns empty Container
, and when isLoggedIn()
returns value - this method will return needed widget
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With