flutter async to sync programming

Viewed 2436

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.

1 Answers

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

Related