简体   繁体   中英

How to use sharedPreference in flutter to stay user loggedin in flutter using a setBool and GetBool

I am practicing a email authentication in flutter and almost everything is over. Now, i want to use sharedPreference to stay the user logged in. I have tried something, but i don't get result. I am using a bool type to get whether user loggedIn or not. But i am very new to this, can you help me in this? and is there anything i am missing out?

This is the sharedPreference static Class i am using

class sharedPreference {
  static String sharedPreferenceUserLoggedInKey = 'userLoggedIn';
  static String sharedPreferenceUserSignedUpKey = 'userSignedUp';

  //saving data to sharedPreference
  static Future<bool> saveUserLoggedInSharedPreference(
      bool isUserLoggedIn) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.setBool(sharedPreferenceUserLoggedInKey, isUserLoggedIn);
  }

  static Future<bool> saveUserSignedUpSharedPreference(
      bool isUserSignUp) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.setBool(sharedPreferenceUserSignedUpKey, isUserSignUp);
  }

  //getting data to sharedPreference
  static Future<bool> getUserLoggedInSharedPreference() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.getBool(sharedPreferenceUserLoggedInKey);
  }

  static Future<bool> getUserSignedUpSharedPreference() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.getBool(sharedPreferenceUserSignedUpKey);
  }

}

This is the signIn button triggering the setBool: SignInButton:

FlatButton(
onPressed: ()
{
HelperFunction.saveUserLoggedInSharedPreference(true);
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => DashBoard(email: email),
          ),
})

The main function

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light
      .copyWith(systemNavigationBarColor: Colors.black));

  runApp(
    DevicePreview(
      enabled: kReleaseMode,
      builder: (context) => FlashChat(),
    ),
  );
}

class FlashChat extends StatefulWidget {
  @override
  _FlashChatState createState() => _FlashChatState();
}

class _FlashChatState extends State<FlashChat> {
  bool isUserLoggedIn;
  bool isUserSignedUp;

  void getLoggedInStatus() async {
    await HelperFunction.getUserLoggedInSharedPreference().then((value) {
      isUserLoggedIn = value;
    });
  }

  void getSignedUpStatus() async {
    await HelperFunction.getUserSignedUpSharedPreference().then((value) {
      isUserSignedUp = value;
    });
  }

  @override
  void initState() {
    getLoggedInStatus();
    getSignedUpStatus();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
          initialRoute: isUserLoggedIn == true
              ? DashBoard.id: WelcomeScreen.id,
          routes: {
            WelcomeScreen.id: (context) => WelcomeScreen(),
            LoginScreen.id: (context) => LoginScreen(),
            RegistrationScreen.id: (context) => RegistrationScreen(),
            DashBoard.id: (context) => DashBoard(),
          },
          debugShowCheckedModeBanner: false,
        );
      });
    });

when the user gets login set

 prefs.setBool("isLogin", True);

and when the user get a logout in logout function put

 pref.clear()

and in splash screen or at starting put this logic

      SharedPreferences prefs = await SharedPreferences.getInstance();
    var isLogin = prefs.getBool("isLogin");

if (isLogin)
{
//Navigate user to the required screen
}
else{
//navigate user to login screen
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM