Navigator.pushReplacement gives Null check operator used on a null value. This time it is - state

Viewed 400

Google signin provider class is not navigating to the next screen. Signin the user works, but the suer has to signin then leave the app and then re-open. After re-opening the app works fine with the user signed in.

Error log gives: [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value E/flutter ( 9884): #0 StatefulElement.state (package:flutter/src/widgets/framework.dart:4789:44) E/flutter ( 9884): #1 Navigator.of (package:flutter/src/widgets/navigator.dart:2730:47) E/flutter ( 9884): #2 GoogleSignInProvider.signInwithGoogle (package:blahblah/google_signin_provider.dart:37:17) E/flutter ( 9884): <asynchronous suspension>

The error points to a "state" in the Navigator class. How do I set it, so the app navigates?

class GoogleSignInProvider extends ChangeNotifier {

final FirebaseAuth _auth = FirebaseAuth.instance;
User user = firebaseAuth.currentUser;
final GoogleSignIn _googleSignIn = GoogleSignIn();

 Future<String> signInwithGoogle(BuildContext context) async {

  try {
    final GoogleSignInAccount googleSignInAccount =
    await _googleSignIn.signIn();
    final GoogleSignInAuthentication googleSignInAuthentication =
    await googleSignInAccount.authentication;
    final AuthCredential credential = GoogleAuthProvider.credential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );
    await _auth.signInWithCredential(credential);
  } on FirebaseAuthException catch (e) {
    print(e.message);
    throw e;
  }

  final User currentUser = FirebaseAuth.instance.currentUser;
  String uid = currentUser.uid;
  if (currentUser != null)
    await usersRef.doc(currentUser.uid).set({'id': uid, 'email': 
 currentUser.email,
      'username': currentUser.displayName, 'photoUrl': 
 currentUser.photoURL,
      'phone': '', 'dob': '', 'sex': ''});

 Navigator.of(context).pushReplacement(
      MaterialPageRoute(builder: (_) => TabScreen()));
  notifyListeners();
return null;
}

Future logout() async {
await _googleSignIn.disconnect();
FirebaseAuth.instance.signOut();
}
}

thanks for the help!

1 Answers

Since you have sound null safety enabled, you do not need to do a null check on currentUser.

Related