Home > Enterprise >  Flutter Null Safety and Firebase authentication error
Flutter Null Safety and Firebase authentication error

Time:12-30

I am using flutter and firebase for my app. I don't know why I am getting error in below code. With degrade version of flutter(Without null safety) it is working fine but after migrating over null safety, I am facing problem here.

class AuthenticationService {

  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  final firebaseUser = FirebaseAuth.instance.currentUser;

  users.User? _userFromFirebase(User user){
    return user != null ? users.User(id: user.uid, email: user.email):null;
  }

  User? user() {
    firebaseAuth.authStateChanges().listen((User? user) {
      if(user == null){
        return null;
      } else {
        return user; //I am getting error here in return statement
      }
    });
  }
  Future loginWithEmail({required String email, required String password}) async {
    try{
      UserCredential result = await firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
      User? user = result.user;
      return _userFromFirebase(user!);
    } catch (e) {
      return e.toString();
    }
  }

  Future register({required String email, required String password}) async {
    try{
      UserCredential result = await firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
      User? user = result.user;
      return _userFromFirebase(user!);
    } catch (e) {
      return e.toString();
    }
  }

}

In User? user(){} method, I am getting error in return statement. Can anyone have idea about it??

I think some small mistake is there which I am not able to identifying it.

The error is :

Error: Can't return a value from a void function.

CodePudding user response:

You can't return something from within the listen callback to the scope of your user() function.

The closest equivalent to what you have now is to return a Future<User?> with something like this:

Future<User?> user() {
  return firebaseAuth.authStateChanges().first()
}

You have to return a Future here (or mark the function as async, which does pretty much the same thing) because the authStateChanges() comes from Firebase asynchronously, and won't yet be available by the time the return statement runs.

I recommend reading up on asynchronous behavior in Flutter/Dart, for example with:

CodePudding user response:

if it is a callback and it has to wait for some time then you have to declare your method as future. because the return type of user is future which takes some time so you have to make the method as future...

hope this works for you

  • Related