Boolean expression must not be null?

前端 未结 4 1106
慢半拍i
慢半拍i 2021-01-23 20:46

Does anyone know why i got the Failed assertion: boolean expression must not be null. If I had logged in and quit the app and open the app again i should be directly in the home

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 21:11

    You have a global approach error. You combine traditional and async/await methods in this code:

    getLoggedInState()async{
        await HelperFunction.getUserLoggedInSharedPreference().then((value){
          setState(() {
            userIsLoggedIn = value;
          });
        });
      }
    

    If you use async/await you should not use then method.

    To implement what you want you should use something like this:

    ...
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: FutureBuilder(
          future: HelperFunction.getUserLoggedInSharedPreference(),
          builder: (context,snapshot) {
            if (snapshot.hasData) {
              // Future is ready. Take data from snapshot
              userIsLoggedIn = snapshot.data; // bool value is here
              return userIsLoggedIn ? HomeScreen() : CompanyLoadingBar();
            } else {
              // Show progress while future will be completed
              return CircularProgressIndicator();
            }
          }
        ),
      );
    }
    ...
    

    And also check what value is returned from HelperFunction.getUserLoggedInSharedPreference(). It seems it returns null because I think you have no already saved value. So you need to specify the default value:

    final value = await SharedPreferences.getInstance().readBool(name) ?? false;
    

提交回复
热议问题