Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I searched google/stackoverflow alot and tried but nothing worked. This is the flow i want:

  1. User launches the app. Splash screen appears.
  2. Login screen appears after splash screen. User logs in.
  3. User kills(closes) the app.
  4. When user relaunches the app, it should show the splash screen followed by the homepage, as user has already logged in once before.
  5. User will only see login page if he/she logs out.

So far 1 and 2 works. But when user kills/closes the app and relaunches it again, instead of being directed to the home page, they are directed to the login page again.

The code for the splash screen:

class _SplashScreenState extends State<SplashScreen> {
@override

void initState() {
super.initState();
startTimer();}



@override
Widget build(BuildContext context) {
return Scaffold(
  body: Center(
    child: Container(
      height: 150,
      width: 150,
      child: new SvgPicture.asset(
          'assets/logo.png'
      ),
    ),
    ),
);
}
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');
print(status);
if (status == true) {
  Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => HomePage());
} else {
  Navigator.pushReplacement(context,  MaterialPageRoute(builder: (BuildContext context) => LoginScreen()));
}
}}

The code for the log out button:

void logoutUser() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs?.clear();
Navigator.pushAndRemoveUntil(
    context,
    MaterialPageRoute(builder: (BuildContext context) => SplashScreen()),
   
    ModalRoute.withName("/login"),
);
}

Sorry for the lengthy post, and really appreciate the help if someone could point out where i've gone wrong. Or if there's any other way to achieve a one-time login in flutter. Thanks!

question from:https://stackoverflow.com/questions/65919130/how-to-use-shared-preferences-to-have-a-one-time-login-in-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
930 views
Welcome To Ask or Share your Answers For Others

1 Answer

Where do you set 'isLoggedIn' pref to true?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...