0

I've this simple login method in my Auth provider class

  Future login(String email, String password) async {
    try {
      AuthResult result = await _firebaseAuth.signInWithEmailAndPassword(
          email: email, password: password);
      FirebaseUser user = result.user;
      var _tokenServer = await user.getIdToken();
      _token = _tokenServer.token;
      _userId = user.uid;
      notifyListeners();
      print("logged in");
      return user.uid;
    } catch (e) {
      print(e);
    }
  }
}

and this getter

 bool get isAuth {
    return _token != null;
  }

And this is my main

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(
          value: Auth(),
        ),
      ],
      child: Consumer<Auth>(
        builder: (ctx, auth, _) => MaterialApp(
          title: 'Flutter Demo',
          // theme: ThemeData(
          //   // primarySwatch: Colors.blue,
          // ),
          theme: ThemeData.dark(),
          home: auth.isAuth ? HomeScreen() : LoginScreen(),
        ),
      ),
    );
  }

If I do login, I'm able to get all the data(token, id etc..) but the page doesn't change and I stay at the login page. What am I doing wrong?

EDIT: I see now that I can redirect to the home screen, but I need to press the back button to get the home Screen

1 Answers1

2

Actually, you don't wrap whole app in the Consumer. The home property will not refresh to change the main route though. You can instead do something like this.

Example:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(
          value: Auth(),
        ),
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        // theme: ThemeData(
        //   // primarySwatch: Colors.blue,
        // ),
        theme: ThemeData.dark(),
        home: Consumer<Auth>(
          builder: (ctx, auth, _) {
            return auth.isAuth ? HomeScreen() : LoginScreen();
          },
        ),
      ),
    );
  }
}

Hope that helps!

Hemanth Raj
  • 32,555
  • 10
  • 92
  • 82