Search code examples
flutterauthenticationinitialization

bool variable is not able to capture if any user is logged in, although print(user) is printing a signed in user (Flutter web app)


Trying to get the status if user is signed in the main function of flutter web app by overriding initstate method. Although, I'm successfully logged in through a sign in screen in the previous run of my app, I always get the value false for isSignedIn, but not true. Below is part of code. Let me know if more details are required.

//Importing necessary packages and files here including material, go_router, firebase_core, firebase_auth etc.

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
User? customer;
bool? isSignedIn;

@override
  void initState() {
    Future<User?> _signedInCustomer() async {
      await _auth.authStateChanges().listen((User? user) {
        print('user=\n$user');
        if (user != null) {
          customer = user;
        } else {
          customer = null;
        }
      });
      return customer;
    }

    bool _isSignedIn(user) {
      if (user != null) {
        return true;
      } else
        return false;
    }

    Future<void> _setIsSignedIn() async {
      isSignedIn = await _signedInCustomer().then((user) => _isSignedIn(user));
      print('isSignedIn = $isSignedIn');
    }

    _setIsSignedIn();
    super.initState();
  }

//I'm using the bool isSignedIn variable as below

late final GoRouter _router = GoRouter(
    initialLocation: "/",
    routes: [
      GoRoute(
        name: "home",
        path: "/",
        builder: (context, state) => MyHomePage(),
      ),
      GoRoute(
          name: "signin",
          path: "/signin",
          pageBuilder: (context, state) =>
              CustomAnimatedNavigation(key: state.pageKey, child: AuthPage())),
      GoRoute(
        name: "orders",
        path: "/orders",
        pageBuilder: (context, state) =>
            CustomAnimatedNavigation(key: state.pageKey, child: MyOrders()),
        redirect: (context, state) async {
          if (isSignedIn!) {
            return "/orders";
          } else if (state.location != '/signin') {
            return "/signin";
          }
          return null;
        },
      ),
    ],
  );
//Code for @override Widget build() here
}

//Order button on first home page trigger the route to signin or orders page like this onPressed: () => context.push('/orders')

Expecting to get value of bool variable isSignedIn to be true but always getting false.


Solution

  • You are using authStateChanges wrong. Try using it like this:

    First define a stream subscription where you define _auth (inside your class):

    late StreamSubscription authStreamSubscription;
    

    Then inside initState:

    authStreamSubscription = _auth.authStateChanges.listen((User?) { 
     setState(() => isSignedIn = user != null);
    });
    

    Then again in your class define the dispose method:

    @override
    void dispose() {
     authStreamSubscription.cancel();
     super.dipose();
    }
    

    Note: you will probably need to import dart:async.