How to use shared preferences to keep user logged in flutter?

后端 未结 5 1973
长发绾君心
长发绾君心 2020-11-30 02:35

I want to keep the user logged in after the user successfully logsin in flutter. I am using a REST API to retrieve the user name and password of the user. But I want to save

5条回答
  •  隐瞒了意图╮
    2020-11-30 03:24

    You can navigate to the Login page if the user details are saved in the storage else to the Home page with the below code

      Future main() async {
          WidgetsFlutterBinding.ensureInitialized();
          SharedPreferences prefs = await SharedPreferences.getInstance();
          var email = prefs.getString('email');
          print(email);
          runApp(MaterialApp(home: email == null ? Login() : Home()));
        }
    

    Save the required user details after the successful login

    class Login extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: RaisedButton(
              onPressed: () async {
                //after the login REST api call && response code ==200
                SharedPreferences prefs = await SharedPreferences.getInstance();
                prefs.setString('email', 'useremail@gmail.com');
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (BuildContext ctx) => Home()));
              },
              child: Text('Login'),
            ),
          ),
        );
      }
    }
    

    clear the details on logout

    class Home extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Home'),
          ),
          body: Center(
            child: RaisedButton(
              onPressed: () async {
                SharedPreferences prefs = await SharedPreferences.getInstance();
                prefs.remove('email');
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (BuildContext ctx) => Login()));
              },
              child: Text('Logout'),
            ),
          ),
        );
      }
    }
    

    Hope it helps!

提交回复
热议问题