简体   繁体   English

无法在颤振中加载共享首选项

[英]Can't load sharedpreferences in flutter

So I was trying to make a guest mode and user mode, where if the token is null, it will return the guest mode page and vice versa.所以我试图制作访客模式和用户模式,如果令牌为空,它将返回访客模式页面,反之亦然。

The problem is that my token is always null that makes it ends up in the guest mode instead of user mode.问题是我的令牌始终为空,这使得它最终处于访客模式而不是用户模式。

The token is null because when I try to debug, the program skipped the token = prefs.getString(_sessionTokenKey);令牌为空,因为当我尝试调试时,程序跳过了token = prefs.getString(_sessionTokenKey); I have checked the _sessionTokenKey storage and there is a token.我已经检查了_sessionTokenKey存储并且有一个令牌。

static void loadToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    token = prefs.getString(_sessionTokenKey);
}

static Widget _homeBuilder(BuildContext context) {
    loadToken();
    print("this is token from route generator");
    print(token);
    if (token == null) {
        return BottomNavBarGuestMode();
    } else {
        return BottomNavBar();
    }
}

static Route<dynamic> generate(RouteSettings settings) {
    switch (settings.name) {
      case Routes.main:
        return MaterialPageRoute(builder: _homeBuilder, settings: settings);
      default:
        return MaterialPageRoute(builder: (_) => RouteErrorPage());
    }    
}

Your loadToken is async.您的loadToken是异步的。 So token is null because you do not wait for an answer of loadToken .因此 token 为空,因为您不等待loadToken的回答。

Solution:解决方案:

Add an await before your your laodToaken() call.在您的laodToaken()调用之前添加await

You are not following the correct approach to use shared preferences.您没有遵循使用共享首选项的正确方法。 Just make a class with your appname and add a static instance for shared preference like this:只需使用您的应用程序名称创建一个类并为共享首选项添加一个静态实例,如下所示:

class AppName{
static SharedPreferences prefs;
}

now in you main method initialise the prefs, also make your main function as async as follows:现在在你的主要方法中初始化首选项,也使你的主要功能异步如下:

Future<void> main() async {
AppName.prefs = await SharedPreferences.getInstance();
}

Since you have the preferences initiated now, you can use it easily.So now change your loadToken method as follows:由于您现在已经启动了首选项,因此您可以轻松使用它。所以现在更改您的 loadToken 方法如下:

String loadToken(){
    final prefs = AppName.prefs;
    token = prefs.getString(_sessionTokenKey);
    return token;
}

And change your _homeBuilder code as below:并更改您的 _homeBuilder 代码如下:

static Widget _homeBuilder(BuildContext context) {
    token = loadToken();
    print("this is token from route generator");
    print(token);
    if (token == null) {
        return BottomNavBarGuestMode();
    } else {
        return BottomNavBar();
    }
}

You might require to import the AppName class wherever required.您可能需要在需要的地方导入 AppName 类。

发现需要使用FutureBuilder(),这样load data方法才能同步运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM