【问题标题】:I have a question about using Shared_Preferences in Flutter我有一个关于在 Flutter 中使用 Shared_Preferences 的问题
【发布时间】:2021-01-05 16:22:14
【问题描述】:

我有一个关于在 Flutter 中使用 Shared_Preferences 的问题。

我的问题是 Shared_Preferences 在模拟器中运行良好,

但当我实际将手机连接到下一行时,我什至没有得到 Shared_Preferences 对象。

void initState() {
    // TODO: implement initState
    (() async {

      final SharedPreferences prefs = await SharedPreferences.getInstance();
      bool res = prefs.getBool('autoLoginKey');
      String id = prefs.getString('autoLoginId');
      String pw = prefs.getString('autoLoginPw');

     
          Navigator.push(
              context, // 기본 파라미터, SecondRoute로 전달
              MaterialPageRoute(
                  builder: (context) =>
                      MainPage()) // SecondRoute를 생성하여 적재
          );
        }
      }
      else {
        Timer(Duration(seconds: 1), () {
          Navigator.pushReplacement(context, MaterialPageRoute(
              builder: (context) => LoginMainScreen()
          )
          );
        });
      }
        })();

    super.initState();
  }

[![在此处输入图像描述][1]][1] [1]:https://i.stack.imgur.com/nZZSC.png

【问题讨论】:

  • 您确定要在异步函数中调用 await 吗?请发布完整代码
  • @Henok 我编辑了我的代码谢谢。
  • @Henok 如果我调试代码,'final SharedPreferences prefs = await SharedPreferences.getInstance();'紧接着,它转到'super.initState();'。
  • 尝试为它创建一个单独的函数,如 initiCode() async { //paste the code here} 并在 initState 中调用此函数。

标签: android flutter dart android-emulator sharedpreferences


【解决方案1】:

尝试将异步函数包装在此

WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  //Call your async function here
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2022-07-20
    • 1970-01-01
    • 2022-11-27
    • 2022-11-10
    • 1970-01-01
    • 2020-03-19
    相关资源
    最近更新 更多