setInt的Flutter共享首选项问题

时间:2020-11-08 20:01:53

标签: flutter

我试图建立一个由3个角色(学生老师和家长)组成的应用。我想到了使用auth更改流和共享首选项实现身份验证。即setInt('usertype',1)表示学生,2表示教师,3表示父母。

这是我的学生注册屏幕,如果用户成功注册,将用户类型设置为1,我也对老师和家长注册屏幕做了同样的操作。

class StudentRegisterScreen extends StatefulWidget {
  final Function toggleView;
  StudentRegisterScreen({this.toggleView});
  @override
  _StudentRegisterScreenState createState() => _StudentRegisterScreenState();
}

class _StudentRegisterScreenState extends State<StudentRegisterScreen> {
  final AuthService _authService = AuthService();

  final _formkey = GlobalKey<FormState>();
  final usertype = await SharedPreferences.getInstance();
  //String name = '';
  //String email = '';
  //String password = '';
  
  @override
  Widget build(BuildContext context) {
    //String _message = '';
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: HexColor(studentPrimaryColour),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Form(
            key: _formkey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                SizedBox(
                  height: 20.0,
                ),
                HeadingText(
                  text: 'Register',
                  size: 60.0,
                  color: Colors.white,
                ),
                Container(
                  height: 20.0,
                  child: HeadingText(
                    text: AuthService().message,
                    size: 20.0,
                    color: Colors.white,
                  ),
                ),
                SizedBox(
                  height: 25.0,
                ),
                RoundedInputField(
                  hintText: 'Name',
                  validator: (val) =>
                      val.isEmpty ? 'Oops! you left this field empty' : null,
                  onChanged: (val) {
                    name = val;
                  },
                ),
                SizedBox(
                  height: 5.0,
                ),
               
                RoundedInputField(
                  hintText: 'Email',
                  validator: (val) => val.isEmpty ? 'enter an email' : null,
                  onChanged: (val) {
                    email = val;
                  },
                ),
                SizedBox(
                  height: 5.0,
                ),
                RoundedInputField(
                    hintText: 'Password',
                    validator: (val) =>
                        val.isEmpty ? 'atleast provide a password' : null,
                    boolean: true,
                    onChanged: (val) {
                      password = val;
                    }),
                SizedBox(
                  height: 5.0,
                ),
                Container(
                  margin: EdgeInsets.symmetric(vertical: 10),
                  width: size.width * 0.8,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(29),
                    child: FlatButton(
                      padding:
                          EdgeInsets.symmetric(vertical: 20, horizontal: 40),
                      color: Colors.white,
                      onPressed: () async {
                        
                        // 
                        //   if (_formkey.currentState.validate()) {
                        //     print(email);
                        //     print(password);
                               usertype.setInt('usertype',1);
                        //     dynamic result =
                        //         await _authService.registerWithEmailpasswd(
                        //             email,
                        //             password,
                        //             name,
                        //            );
                        //    
                      },
                      child: HeadingText(
                        color: HexColor(studentPrimaryColour),
                        text: 'Register',
                        size: 12.0,
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 15.0,
                ),
                InkWell(
                  onTap: () {
                    // Navigator.pop(context);
                    widget.toggleView();
                  },
                  child: HeadingText(
                    text: 'Already registered?',
                    color: Colors.white,
                    size: 10,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


但我收到错误消息

I/flutter (13157): 0
E/flutter (13157): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'setInt' was called on null.
E/flutter (13157): Receiver: null
E/flutter (13157): Tried calling: setInt("usertype", 1)


下面是我现在的包装器类,我想在继续进行之前将值打印到控制台上,我将实现用于显示不同用户屏幕的切换案例


class Welcomescreen extends StatefulWidget {
  @override
  _WelcomescreenState createState() => _WelcomescreenState();
}

class _WelcomescreenState extends State<Welcomescreen> {
  SharedPreferences userDetails;
  int usertype;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkUserType();
  }

  void checkUserType() async {
    userDetails = await SharedPreferences.getInstance();
    setState(() {
      usertype = userDetails.getInt('usertype') ?? 0;
    });

    print(usertype);
  }

  @override
  Widget build(BuildContext context) {
    //final user = Provider.of<UserModel>(context);
    return Body();
  }
}


1 个答案:

答案 0 :(得分:0)

userType通过创建SharedPreference.getInstance()来引用将来值final userType = await SharedPrefence.getInstance(),您告诉代码调用userType将返回Future of SharedPrefence.getInstance(),直到解析为SharedPreference类,您实际上正在等待它(使用await不会做任何事情,因为您实际上不在ayn函数内部)

尝试这样称呼它:

onPressed: () async {
    (await usertype).setInt('usertype',1);
     // or maybe (userType).setInt('usertype',1);
}

userType将替换为您所引用的值(await SharedPreference.getInstance()

程序看起来像这样:

onPressed: () async {
    (await SharedPreference.getInstance()).setInt('usertype',1);
}

首先它需要等待狂欢,之后您才可以实际调用其方法