0
votes

I have a FirebaseActions class which is doing signup and signin works for me. I added a getCurrentUser method in it. I'm calling that function from my HomeScreen widget. I need to put the returned value(type= FirebaseUser) into a variable in my HomeScreen to reach loggedInUser.email. But I get this error. My question; is there any way to get a FirebaseUser type data into a Future type variable? When I write this function in HomeScreen instead of FirebasAction class, it works but is it the best practice?

FirebaseActions class

static getCurrentUser(context) async {
    final user = await _auth.currentUser().catchError((error) {
      Scaffold.of(context).showSnackBar(AppSnackBar.appSnackBar(error.message));
    });

    if (user != null) {
      return user;
    }
  }

HomeScreen widget

class _HomeScreenState extends State<HomeScreen> {

  FirebaseUser loggedInUser;

  @override
  void initState() {
    super.initState();
    loggedInUser = FirebaseActions.getCurrentUser(context);
    print(loggedInUser.toString());
  }
3

3 Answers

2
votes

You are getting this error because you didn't specify a return type in your getCurrentUser() function.

Replace your code with the one below and everything will work fine.

To solve this issue: Check the code below: It works perfectly fine:

Firebase Action Class

// give your function a return type
static Future<FirebaseUser> getCurrentUser(context) async {
    final user = await _auth.currentUser().catchError((error) {
      Scaffold.of(context).showSnackBar(AppSnackBar.appSnackBar(error.message));
    });

    if (user != null) {
      return user;
    }
  }

Home Screen Widget

class _HomeScreenState extends State<HomeScreen> {

  FirebaseUser loggedInUser;

  @override
  void initState() {
    super.initState();
    call the function here
    logInUser();
    print(loggedInUser.toString());
  }

I hope this helps

UPDATE

// create a new function to log in user
void logInUser() async {
 // await the result because you are invoking a future method
    loggedInUser = await FirebaseActions.getCurrentUser(context);
}
2
votes

You are not specified return type of method and also method is async, so you have to put await where you are calling.

 static Future<FirebaseUser> getCurrentUser(context) async {

also, add await where you are calling.

loggedInUser = await FirebaseActions.getCurrentUser(context);

update:

create new function and call in that function.

callme() async{  
 loggedInUser = FirebaseActions.getCurrentUser(context);
    print(loggedInUser.toString());
}

initstate:

 @override
  void initState() {
    super.initState();
    callme();
  }
1
votes

Here's how I handle async functions in my initstate:

FirebaseActions.getCurrentUser(context).then((val){loggedInUser = val});

Also make sure you specify the return type in your asynchronous function.

Future<FirebaseUser> getCurrentUser(context) async {...