SharedPreference无法在我的Flutter应用程序上运行

时间:2019-12-21 05:51:10

标签: flutter dart

我想使用Flutter的SharedPreference保存用户首选项。但是注册的首选项在newstart时全部为空(如果启动我的应用程序,则无法保存会话),我的共享首选项在我的flutter项目中不起作用。

我的代码:

var value;
getProf() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  setState(() {
    value = prefs.getInt('value');


    _loginStatus = value == 1 ? LoginStatus.signIn : LoginStatus.notSignIn;
  });
}

login() async {
  final response = await http.post(
      "https://smartnote12.000webhostapp.com/login/api/login.php",
      body: {"username": username, "password": password});
  final data = jsonDecode(response.body);
  int value = data['value'];
  String pesan = data['message'];
  if (value == 1) {
    setState(() {
      _loginStatus = LoginStatus.signIn;

      print(pesan);
    });
  } else {
    _showAlert(context);
  }
}

void _showAlert(BuildContext context) {
  showDialog(
      context: context,
      builder: (context) => AlertDialog(
            title: Text("Login"),
            content: Text("Password & Username Salah"),
          ));
}

在这里,我将函数状态称为“状态”,但它不起作用

@override
void initState() {
  // TODO: implement initState
  super.initState();
  getProf();
}

@override
Widget build(BuildContext context) {
  switch (_loginStatus) {
    case LoginStatus.notSignIn:
      return Scaffold(
        resizeToAvoidBottomPadding: false,
        body: Container(

1 个答案:

答案 0 :(得分:0)

不要在initState()中调用getProf()。您可以使用FutureBuilder

@override
Widget build(BuildContext context) {
 new FutureBuilder<LoginStatus>(
    future: getProf(),
    builder: (BuildContext context, AsyncSnapshot<LoginStatus> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.waiting:
          return Text('Loading');
        case ConnectionState.done:
          if (snapshot.hasData) {
            loginStatus = snapshot.data;
            if(loginStatus.notSignIn) {
             // login button is here
             return Container(child: Text('not signed in'));
            }
            else {
             return Container(child: Text('Signed in'));
            }
          } else {
           return  Container(child: Text('error'));
          }
      }
    },
  )
 }