LoginScreen中共享的首选项中的问题。扑 [英] Problem in Shared Preferenced in LoginScreen. Flutter

查看:50
本文介绍了LoginScreen中共享的首选项中的问题。扑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帮助并向我详细解释如何修改我的代码。我是Flutter的初学者,现在我正在执行任务,其本质是在登录屏幕中使用Shared Preferenced,并将用户数据保存在FireBase中。当用户首次输入数据时,他进入了主屏幕,但是当用户退出应用程序并尝试再次登录时,应该是因为他不需要输入密码并再次登录。

help and explain to me in detail please how can I modify my code. I am beginner in Flutter and now I am doing tasks, the essence of which is the use of Shared Preferenced in the Login Screen and saving the user data in FireBase. When the user first entered the data, he entered the Home screen, but when the user exits the application and tries to log in again, it should be that he does not need to enter the password and login again.

此外,我还剔除了这样的错误

    import 'package:flutter/material.dart';
import 'package:logining/home_screen/home_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:shared_preferences/shared_preferences.dart';


class LoginScreen extends StatefulWidget {
  @override
  LoginScreenState createState() {
    return new LoginScreenState();
  }
}
enum LoginStatus{
  notSignIn,
  signIn,
}

class LoginScreenState extends State<LoginScreen> {
  LoginStatus _loginStatus = LoginStatus.notSignIn;
  String _email, _password;
  bool _obscureText = true;




  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn googleSignIn = GoogleSignIn();
  TextEditingController email = new TextEditingController();
  TextEditingController password = new TextEditingController();
  SharedPreferences sharedPreferences;


  Future<FirebaseUser> _signInGoogle() async{
    GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
    GoogleSignInAuthentication gSa =await googleSignInAccount.authentication;

    FirebaseUser user = await _auth.signInWithGoogle(
      idToken: gSa.idToken,
      accessToken: gSa.accessToken
      );
      print('User Name : ${user.displayName}');
      return Navigator.push(context, MaterialPageRoute(builder: (context) => HomeScreen(user: user)));
  }

  safePref()async{
   SharedPreferences preferences = await SharedPreferences.getInstance();
   setState((){
     preferences.setString('email', _email);
     preferences.setString('password', _password);
     preferences.commit();
   }); 
  }
  var value;
  getPref()async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    setState(() {
      value = preferences.getInt('password');
      value = preferences.getInt('email');

      _loginStatus = value == 1 ? LoginStatus.signIn :LoginStatus.notSignIn;
    });
  }
  @override
  void initState(){
    super.initState();
    getPref();
  }

  @override
  Widget build(BuildContext context) {
    switch(_loginStatus){
      case LoginStatus.notSignIn:
        return Scaffold(
        appBar: AppBar(
          title: Text('Login'),
        ),
        resizeToAvoidBottomPadding: false,
        body: ListView(children: <Widget>[
          Container(
            child: Form(
              key: _formKey,
              autovalidate: true,
              child: Column(
                children: <Widget>[
                  SizedBox(
                    height: 50,
                  ),
                  Padding(
                    child: Image.asset(
                      'images/logo.png',
                      width: 100.0,
                      height: 100.0,
                    ),
                    padding: EdgeInsets.fromLTRB(50, 0, 50, 40),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(25, 0, 50, 10),
                    child: TextFormField(
                      controller: email,
                      validator: (email) {
                        if (email.isEmpty) {
                          return 'Provide an Email';
                        }
                      },
                      style: TextStyle(
                        color: Color(0xFF01579B),
                        fontSize: 18.0,
                      ),
                      decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(30),
                          ),
                          hintText: 'Enter your Email',
                          labelText: "Email",
                          icon: Padding(
                            padding: EdgeInsets.only(top: 20.0),
                            child: Icon(Icons.email),
                          )),
                      onSaved: (email) => _email = email,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(25, 0, 50, 10),
                    child: TextFormField(
                      controller: password,
                      validator: (password) {
                        if (password.isEmpty) {
                          return 'Provide an password';
                        }
                      },
                      obscureText: _obscureText,
                      style: TextStyle(
                        color: Color(0xFF01579B),
                        fontSize: 18.0,
                      ),
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                        hintText: 'Enter your password',
                        labelText: "Password",
                        icon: Padding(
                          padding: EdgeInsets.only(top: 15.0),
                          child: Icon(Icons.lock),
                        ),
                        suffixIcon: GestureDetector(
                          onTap: () {
                            setState(() {
                              _obscureText = !_obscureText;
                            });
                          },
                          child: Icon(
                            _obscureText
                                ? Icons.visibility
                                : Icons.visibility_off,
                            semanticLabel: _obscureText
                                ? 'show password'
                                : 'hide password',
                          ),
                        ),
                      ),
                      onSaved: (password) => _password = password,
                    ),
                  ),
                  Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: RaisedButton(
                            color: Color(0xFFD50000),
                            textColor: Color(0xFFFFFFFF),
                            child: Text('Login with Google'),
                            onPressed:(){ _signInGoogle().then((FirebaseUser user){
                              print(user);
                            }).catchError((onError){
                              print(onError);
                            });

                            }
                          ),

                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: RaisedButton(
                            color: Color(0xFF448AFF),
                            textColor: Color(0xFFFFFFFF),
                            child: Text('Login'),
                            onPressed: signIn,
                          ),
                        ),
                  ]),
                      Padding(
                          padding:
                              EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                          child: FlatButton(
                            textColor: Color(0xFF448AFF),
                            child: Text('Forgot Password'),
                            onPressed: () {
                              print('onPressed');
                            },
                          ),
                        ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.fromLTRB(50, 70, 0, 10),
                        child: Text(
                          'Still do not have an account ',
                          style: TextStyle(color: Color(0xFF9E9E9E)),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.fromLTRB(0, 70, 30, 10),
                        child: FlatButton(
                          textColor: Color(0xFF448AFF),
                          child: Text('registration'),
                          onPressed: () {
                            Navigator.of(context).pushNamedAndRemoveUntil(
                                '/registration', (Route<dynamic> route) => false);
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ]),
      );
        break;
      case LoginStatus.signIn:
        return HomeScreen();
        break;
    }

  }
Future<void> signIn() async {
    final formState = _formKey.currentState;
    if(formState.validate()) {

      setState(() {
       _loginStatus = LoginStatus.signIn;
       formState.save();
      });
      try {
        FirebaseUser user = await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password); 
      }catch(e){
        print(e.message);
      }
    }
}
}


推荐答案

您拥有as字符串值,并尝试读取为int值,这就是问题所在。您应该首先将您的电子邮件和密码读为String,然后将其解析为int。

You have as String value and try to read as int value here's the problem . You should first read as String your email and password and then parse them to int.

 var value;
 getPref()async{

SharedPreferences preferences = await SharedPreferences.getInstance();

setState(() {
  value = preferences.getString('password');
  value = preferences.getString('email');
  _loginStatus = int.parse(value) == 1 ? LoginStatus.signIn :LoginStatus.notSignIn;
});
}

这篇关于LoginScreen中共享的首选项中的问题。扑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆