This is my UserAuthProvider:
class UserAuthProvider extends ChangeNotifier {
bool _isSignedIn = false;
bool get isSignedIn => _isSignedIn;
void userSignedIn() {
_isSignedIn = true;
notifyListeners();
}
void userSignedOut() {
_isSignedIn = false;
notifyListeners();
}
}
I want to show HomePage when _isSignedIn
is true, and I want to show SignInPage when _isSignedIn
is false. User can sign in and sign out in both pages, so I want to show two pages continuously based on provider value change.
So I created MainPage. Here is my MainPage code:
class MainPage extends StatefulWidget {
const MainPage({super.key});
@override
State<MainPage> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainPage> {
Map pages = {
true: HomePage(), false: LoginPage()
}
@override
Widget build(BuildContext context) {
return Consumer<UserAuthProvider>(builder: (context, provider, _){
return pages[provider.isSignedIn];
});
}
}
However, this code does not work properly. When I run the app first time, it shows LoginPage because initial value of _isSignedIn
is false. But when I change _isSignedIn
value using context.read<UserAuthProvider>().userSignedIn();
inside LoginPage
, the page does not change.
How to fix this problem? Or can you suggest me better approach on showing different page based on provider value?
2
Answers
You might forget use
ChangeNotifierProvider
I guess