Reputation: 881
I tried to implements this Authentification here Firebase with Porvider here the issue is I want to save the state of variable loggedIn even I close and reponning the app so I used this code but dont work
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<AuthenticationService>(builder: (_, auth, __) {
if (auth.getCurrentUser() != null)
return HomeView();
else
return TermsView();
});
}
}
here method to get current user
Future getCurrentUser() async {
FirebaseUser _user ;
_user = await FirebaseAuth.instance.currentUser();
return _user ;
}
Is there a way to check signing in inside Consumer
?
Upvotes: 2
Views: 966
Reputation: 267384
You need to use FirebaseAuth.currentUser
to check if user is signed in or not, I am using FutureBuilder
inside Consumer
for this work.
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
ChangeNotifierProvider<Auth>(
create: (_) => Auth(),
child: MaterialApp(home: MyApp()),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<Auth>(
builder: (_, auth, __) {
return FutureBuilder<FirebaseUser>(
future: auth.currentUser,
builder: (context, snapshot) {
if (snapshot.hasData) return HomeScreen();
return LoginScreen();
},
);
},
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFF4C3E13),
appBar: AppBar(title: Text('Home Screen')),
floatingActionButton: FloatingActionButton.extended(
label: Text('Sign out'),
onPressed: () async {
final auth = Provider.of<Auth>(context, listen: false);
await auth.signOut();
},
),
);
}
}
class LoginScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Login Screen')),
body: Center(
child: RaisedButton(
onPressed: () async {
final auth = Provider.of<Auth>(context, listen: false);
await auth.signIn(email: '[email protected]', password: 'user1234');
},
child: Text('Sign In'),
),
),
);
}
}
class Auth with ChangeNotifier {
final _auth = FirebaseAuth.instance;
Future<void> signOut() async {
await _auth.signOut();
notifyListeners();
}
Future<void> signIn({@required String email, @required String password}) async {
await _auth.signInWithEmailAndPassword(email: email, password: password);
notifyListeners();
}
Future<FirebaseUser> get currentUser async {
return await _auth.currentUser();
}
}
Upvotes: 4