7

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
  • I feel your pain. Commented Feb 25, 2023 at 0:49

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

it works! awesome quick response. but how does this work, or is there any good documentation out there that explains futurebuilders in more detail?
look at this explanation: medium.com/nonstopio/…
For handling some async operations I'd recommend to look FutureBuilder and StreamBuilder on the official site api.flutter.dev/flutter/widgets/widgets-library.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.