'Flutter sign in with google lost authentication when the internet connection lost, how to re-auth it?

We are currently building an app that requires only google sign in and communicate with the Firebase depending on those data that we get with sign in.

The problem is this; after logging in to the app if the user lost internet connection and then re-establishes that connection without closing the app, FirebaseAuth.currentUser is not null but at the same time the user is not authenticated so the functions that i need to communicate with the DB is not working.

My question is simply this;

How do i check for the authentication and then re-authanticate the user.

My signin method is below, i tried to re-sign in every time when user enters some certain pages but that just not seemed good but does solves the problem. Is there a optimized way?

Future<String> signInWithGoogle() async {
    // Trigger the authentication flow
    final GoogleSignInAccount? googleUser = await _googleSignIn!.signIn();

    // Obtain the auth details from the request
    final GoogleSignInAuthentication? googleAuth =
        await googleUser!.authentication;

    // Create a new credential
    final GoogleAuthCredential credential = (GoogleAuthProvider.credential(
      accessToken: googleAuth!.accessToken,
      idToken: googleAuth.idToken,
    ) as GoogleAuthCredential);

    // Once signed in, return the UserCredential
    final UserCredential? authResult =
        await _auth!.signInWithCredential(credential);
    final User? user = authResult!.user;

    //assert(user!.isAnonymous);
    assert(await user!.getIdToken() != null);

    final User? currentUser = _auth!.currentUser;
    assert(user!.uid == currentUser!.uid);

    return 'signInWithGoogle succeeded: $user';
  }

Edit:

We were using connectivity_plus plugin so we created a listener for it and if the user changes its connection to wifi or mobile we simply re-signin them. It worked for us it may have work for you as well;

@override
 void initState() {
   subscription = Connectivity()
       .onConnectivityChanged
       .listen((ConnectivityResult result) {
     if (result == ConnectivityResult.mobile ||
         result == ConnectivityResult.wifi ||
         result == ConnectivityResult.ethernet) {
       Login().signInWithGoogle();
     }
     print("${result}");
   });
   // TODO: implement initState
   super.initState();
 }
 dispose() {
   super.dispose();

   subscription.cancel();
 }


Solution 1:[1]

The Flutter Firebase docs have a re-authenticate user option and it sounds quite similar to your situation.

Re-authenticate a user

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Haany Ali