Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter async to sync programming

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.

like image 808
cas Avatar asked Oct 16 '19 14:10

cas


People also ask

What is async and sync in Flutter?

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.

Is Flutter async or sync?

Dart and Flutter has great support for Asynchronous Operations .

Is Dart async or sync?

Dart uses Future objects to represent asynchronous operations.

What is asynchronous programming in Flutter?

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.


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

like image 99
Andrey Turkovsky Avatar answered Nov 13 '22 05:11

Andrey Turkovsky