如何保持用户登录颤振

时间:2021-05-31 08:53:04

标签: flutter dart sharedpreferences flutter-sharedpreference

我昨天发布了这个问题,但我没有得到任何有效的答案。我目前的情况是我可以成功登录用户,但是当我重新启动应用程序时,我必须再次登录,因此我需要在共享首选项中保存用户的详细信息,以便用户可以在整个会话中保持登录状态,直到注销。但我无法做到这一点,所以请帮助我。提前致谢

登录.dart:

Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(3, 9, 23, 1),
      body: Container(
          padding: EdgeInsets.only(
            top: 100,
            right: 30,
            left: 30,
          ),
          child: SingleChildScrollView(
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  FadeAnimation(
                      1.2,
                      Container(
                        padding: EdgeInsets.all(70.0),
                        margin: EdgeInsets.only(bottom: 50.0),
                        decoration: BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage(
                                    'assets/images/trakinglogo.png'))),
                      )),
                  SizedBox(
                    height: 30,
                  ),
                  FadeAnimation(
                      1.5,
                      Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Colors.white),
                        child: Column(
                          children: <Widget>[
                            Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom:
                                          BorderSide(color: Colors.grey[300]))),
                              child: TextFormField(
                                controller: _emailController,
                                onFieldSubmitted: (_) =>
                                    FocusScope.of(context).nextFocus(),
                                textInputAction: TextInputAction.done,
                                validator: (value) {
                                  if (value.isEmpty) {
                                    return 'Email is required';
                                  }
                                  return null;
                                },
                                decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintStyle: TextStyle(
                                        color: Colors.grey.withOpacity(.8)),
                                    hintText: "Votre adresse mail"),
                              ),
                            ),
                            Container(
                              decoration: BoxDecoration(),
                              child: TextFormField(
                                controller: _passwordController,
                                validator: (value) {
                                  if (value.isEmpty) {
                                    return 'Password is required';
                                  }
                                  return null;
                                },
                                obscureText: _isHidden,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintStyle: TextStyle(
                                      color: Colors.grey.withOpacity(.8)),
                                  hintText: "Mot de passe",
                                  suffix: InkWell(
                                      onTap: _togglePasswordView,
                                      child: Icon(
                                        _isHidden
                                            ? (CommunityMaterialIcons
                                                .eye_outline)
                                            : (CommunityMaterialIcons.eye_off),
                                        color: Color(0xFF939394),
                      
                  SizedBox(
                    height: 40,
                  ),
                  FadeAnimation(
                      1.8,
                      Center(
                          child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                child: RaisedButton(
                                  textColor: Colors.white,
                                  color: kPrimaryColor,
                                  child: Text("Se connecter"),
                                  onPressed: () async {
                                    if (_formKey.currentState.validate()) {
                                      showDialog(
                                          context: context,
                                          builder: (BuildContext context) {
                                            return Center(
                                              child:
                                                  CircularProgressIndicator(),
                                            );
                                          });
                                      await loginUser();
                                    }
                                    /*  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => MyWidget()),
                                    );*/
                                    // Navigator.pushNamed(context, 'Mywidget');
                                  },
                                  shape: new RoundedRectangleBorder(
                                    borderRadius:
                                        new BorderRadius.circular(30.0),
                                  ),
                                ),
                                width: 250,
                                padding: EdgeInsets.all(15),
                              )
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              AlreadyHaveAnAccountCheck(
                                press: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) {
                                        return SignUp();

 void loginUser() async {
    // if (_formKey.currentState.validate()) {
    setState(() {
      _isLoading = true;
    });
    String email = _emailController.text;
    String password = _passwordController.text;

    authentication.login(email, password).then((user) {
      if (user != null)
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => MyWidget()));
    }).catchError((error) {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text(error.toString())));
    });

    setState(() {
      _isLoading = false;
    });
  }

这是登录功能:

Future<User> login(String email, String password) async {
  await checkInternet();

  Map<String, String> headers = {
    'Content-type': 'application/json',
    'Accept': 'application/json',
  };
  Map<String, String> body = {'email': email, 'password': password};

  var response = await http.post(Uri.parse(ApiUtil.AUTH_LOGIN),
      headers: headers, body: jsonEncode(body));
  switch (response.statusCode) {
    case 200:
      var body = jsonDecode(response.body);
      var data = body['user'];
      User user = User.fromJson(data);
      Track track = Track.fromJson(body);

      if (body['code'] == 0) {
        SharedPreferences localStorage =
        await SharedPreferences.getInstance();
        localStorage.setInt('id', body['user']['id']);
        localStorage.setString('adress', body['user']['adress']);
        localStorage.setString('phone', body['user']['phone']);
        localStorage.setString('access_token', body['access_token']);
        localStorage.setString('user', json.encode(body['user']));
        String user = localStorage.getString('user');

      }
      return user;
    case 500:
      throw ('Erreur serveur');
      break;

    case 400:
      throw LoginFailed();
    default:
      throw ('connection timeout');
      break;
  }
}

2 个答案:

答案 0 :(得分:1)

当我第一次登录时,我将数据保存在共享首选项中

 ApiRepository.get().login(LoginRequest(username: _emailController.text, password: _passwordController.text)).then((response) async {
  if (response != null) {
    //save on the shared preferences that the user is logged in
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(SHARED_LOGGED, true);
    await prefs.setString(SHARED_USER, _emailController.text);
    await prefs.setString(SHARED_PASSWORD, _passwordController.text);
  }
}).catchError((error) { 
});

每次我打开应用程序时,我都会有一个闪屏,在这里我会进行隐式登录,然后跳过登录页面并将用户带到主页

void checkUserIsLogged() async {
    final prefs = await SharedPreferences.getInstance();
    if ((prefs.getBool(SHARED_LOGGED) != null) && prefs.getBool(SHARED_LOGGED)) {
      ApiRepository.get().login(LoginRequest(username: prefs.getString(SHARED_USER), password: prefs.getString(SHARED_PASSWORD))).then((response) {
        if (response != null) {
          //"do something"
        }
      }).catchError((error) {
        
      });
    } else {

    }
  }

完整代码 SplashPageLoading.dart

class SplashPageLoading extends StatefulWidget {
  @override
  _SplashPageLoadingState createState() => _SplashPageLoadingState();
}

class _SplashPageLoadingState extends State<SplashPageLoading> {
  bool _doLogin = false;

  @override
  void initState() {
    super.initState();

    new Future.delayed(const Duration(seconds: 3), () => checkUserIsLogged());
  }

  void checkUserIsLogged() async {
    final prefs = await SharedPreferences.getInstance();
    if ((prefs.getBool(SHARED_LOGGED) != null) && prefs.getBool(SHARED_LOGGED)) {
      setState(() {
        _doLogin = true;
      });
      ApiRepository.get().login(LoginRequest(username: prefs.getString(SHARED_USER), password: prefs.getString(SHARED_PASSWORD))).then((response) {
        if (response != null) {
          Navigator.of(context).pushReplacementNamed(HomePage.routeName);
        }
      }).catchError((error) {
        Navigator.of(context).pushReplacementNamed(LoginPage.routeName);
      });
    } else {
      new Future.delayed(const Duration(seconds: 1), () => Navigator.of(context).pushReplacementNamed(LoginPage.routeName));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          _doLogin ? "Login.." : "No data for login",
          style: TextStyle(color: Colors.black),
        ),
      ),
    );
  }
}

字符串.dart

const String SHARED_LOGGED = "USER_IS_LOGGED";
const String SHARED_USER = "USER";
const String SHARED_PASSWORD = "PASSWORD";

shared preferences library

答案 1 :(得分:0)

SplashPageLoading.dart :

class SplashPageLoading extends StatefulWidget {
      @override
      _SplashPageLoadingState createState() => _SplashPageLoadingState();
    }
    
    class _SplashPageLoadingState extends State<SplashPageLoading> {
      bool _doLogin = false;
      Authentication authentication = Authentication();
    
      static const String SHARED_LOGGED = "USER_IS_LOGGED";
      static const String SHARED_USER = "USER";
      static const String SHARED_PASSWORD = "PASSWORD";
    
      @override
      void initState() {
        super.initState();
    
        new Future.delayed(const Duration(seconds: 3), () => checkUserIsLogged());
      }
    
      void checkUserIsLogged() async {
        final prefs = await SharedPreferences.getInstance();
        if ((prefs.getBool(SHARED_LOGGED) != null) &&
            prefs.getBool(SHARED_LOGGED)) {
          setState(() {
            _doLogin = true;
          });
          authentication
              .login(prefs.getString(SHARED_USER), prefs.getString(SHARED_PASSWORD))
              .then((user) {
            if (user != null) {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => MyWidget()),
              );
    
              // Navigator.of(context).pushReplacementNamed('/splash');
            }
          }).catchError((error) {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => MyWidget()),
            );
    
            //  Navigator.of(context).pushReplacementNamed('/splash');
          });
        } else {
          new Future.delayed(const Duration(seconds: 1),
              () => Navigator.of(context).pushReplacementNamed('/'));
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Text(
          _doLogin ? "Login.." : "",
          style: TextStyle(color: Colors.white),
        );
      }
    }