【问题标题】:How can I get preferences from shared preferences in a method that can't by async in Flutter?如何在 Flutter 中无法通过异步方法从共享首选项中获取首选项?
【发布时间】:2021-11-21 02:33:45
【问题描述】:

我想获取共享首选项的布尔值来决定应该加载哪个小部件,但是该方法不能是异步的或布尔值不能获取值,因为它不允许“等待”该值。我已经尝试修复它,但它大多失败,因为“家”无法接收未来的小部件......,还有其他方法可以做到这一点吗?

void main() => runApp(MyApp());
setloginbool() async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setBool("savelogin", true);
}

Future<bool> getloginbool() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool savelogin = prefs.getBool("savelogin") ?? false;
  return savelogin;
}



class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'KHS Plan',
      theme: (ThemeData(
        textTheme: const TextTheme(
          bodyText1: TextStyle(fontSize: 14)
        )
      )),
      home: checkifpassword(),
    );
  }

}
Widget checkifpassword() {
    bool s = await getloginbool();
    if(s){
      return const Login();
    } else {
      return const MyHomePage();
    }
  }


//This does not work as well
checkifpassword() async {
  bool s = await getloginbool();
    if(s){
      return const Login();
    } else {
      return const MyHomePage();
    }
}

【问题讨论】:

  • 好的,您想从checkifpassword() 加载home 上的小部件?
  • 是的,我也想用 bool 来决定加载哪个

标签: flutter asynchronous async-await sharedpreferences


【解决方案1】:

你可以在Home上使用FutureBuilder

 Future<bool> checkifpassword() async {
//perfrom your async operation and return bool
    return await Future.delayed(Duration(seconds: 2), () {
      return true;

    });
  }

还有home

 home: FutureBuilder<bool>(
          future: checkifpassword(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (snapshot.data!) {// for true
                return Login();;
              } else return MyHomePage();
            }
            /// check others state

            return Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            );
          },
        )

【讨论】:

  • 非常感谢!
  • 很高兴为您提供帮助,您也可以查看hive 并让main方法异步。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-13
  • 1970-01-01
  • 2019-10-01
  • 2019-04-28
相关资源
最近更新 更多