-2

I have some code like this :

  Future<FirebaseUser> _getUser() async {
    return await _fireAuth.currentUser();
  }

  bool get isSignedIn {
    _getUser().then((value) {
      return value != null;
    }).catchError((err) {
      print("Error While knowing isSignedIn --> $err");
    });
  }

Basically, how do I make the code wait while it's getting the data from the future function i.e _getUser() and then return the result via the getter i.e isSignedIn. Using this code the result of the isSignedIn getter is null

I'm still new in Flutter. Your help would be much appreciated.

L.Goyal
  • 773
  • 2
  • 6
  • 23
  • 1
    Take a look at the answer of this post : https://stackoverflow.com/questions/54515186/async-await-then-in-dart-flutter/54515559 – Muldec Aug 01 '20 at 07:32

4 Answers4

0

U'll have to return a Future<bool> as you are calling an async function _getUser()

Future<bool> get isSignedIn async {
  try { 
    var user = await _getUser(); // wait for the function to finish
    return user != null;
  catch (error) {
    print("Error While knowing isSignedIn --> $err");
  }
}
Navaneeth P
  • 1,428
  • 7
  • 13
  • Actually it is almost the same thing as the _getUser function I made. Using this I'll have to write the then method where I'll be using this getter. That's the thing I was avoiding. – L.Goyal Aug 01 '20 at 07:44
  • You can't do that if you want the result of the `async` function `_getUser()`. – Navaneeth P Aug 01 '20 at 07:46
0
Future<bool> get isSignedIn async {
  try { 
    var user = await _getUser(); // wait for the function to finish
    return Future.value(user != null);
  catch (error) {
    print("Error While knowing isSignedIn --> $err");
  }
}

You can try it.

Rohit Soni
  • 1,300
  • 6
  • 12
0

If I understand correctly, I believe you’re trying to get the value returned by the function in your .then(). You can’t. At least not in the way you’re trying to do it.

As I understand it, the return value of the .then() can be used to as the parameter for the next .then(), if you’re chaining them. E.g. getuser().then(({return value of getUser})) => user).then(({this is the user}) => user.uid).then(({this is the user.uid})) ; //...etc

If you want to capture that value computed inside the .then(), you have to have a variable outside, whose value will hold the result.

E.g.

var myuser;
getUser().then((user) => myuser = user);

Not exactly your code but you get it.

Otherwise, I think best practice is to avoid using then when possible. Using await allows you to write code that looks synchronous and is easier to read.

E.g. var user = await getUser()

Here, you dont need .then() at all

lenz
  • 2,193
  • 17
  • 31
0

Actually I think what you’re wanting is a Stream. When the user logs in or out, your Stream gets updated.

Stream<FirebaseUser> get isSignedIn => _fireauth.onAuthChanged; 
lenz
  • 2,193
  • 17
  • 31