Flutter : How to keep user logged in and make logout
You can make an entry in Shared preference after getting response code 200 from api.
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs?.setBool("isLoggedIn", true);
then you can navigate user after checking status from shared preference
Future<void> main() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var status = prefs.getBool('isLoggedIn') ?? false;
print(status);
runApp(MaterialApp(home: status == true ? Login() : Home()));
}
Update :-
Another way of doing it is you can also add your logic into splash screen and splash screen should be entry point in your app
class SplashScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _SplashScreenState();
}
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
// TODO: implement initState
super.initState();
startTimer();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/clinician_splash.png"),
fit: BoxFit.cover),
),
),
);
}
void startTimer() {
Timer(Duration(seconds: 3), () {
navigateUser(); //It will redirect after 3 seconds
});
}
void navigateUser() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
var status = prefs.getBool('isLoggedIn') ?? false;
print(status);
if (status) {
Navigation.pushReplacement(context, "/Home");
} else {
Navigation.pushReplacement(context, "/Login");
}
}
}
For logout add below functionality in onPress event of logout button :
void logoutUser(){
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs?.clear()
Navigator.pushAndRemoveUntil(
context,
ModalRoute.withName("/SplashScreen"),
ModalRoute.withName("/Home")
);
}
For security :-
Here in example I have used SharedPreferences which is not secure.for security you can change SharedPreferences to flutter_secure_storage.
https://pub.dev/packages/flutter_secure_storage#-readme-tab-