首页 > 解决方案 > Flutter ios 共享首选项显示 setstring on null 错误

问题描述

我有我的颤振应用程序,登录后我调用共享偏好来存储一些值,例如令牌、用户 ID 等。所有这一切都在 ios 和 android 上运行良好。突然现在在 ios 上,它给了我 NoSuchMethodError: The method 'setString' was called on null

这是代码片段。

try {
          //final jsonResponse = json.decode(responseJson);
          Login login1 = new Login.fromJson(responseJson);
          token = login1.token;
          print(login1.fleetID);

          await AuthUtils.insertDetails(_sharedPreferences, responseJson);
        } catch (Err) {
          print("ERrro is at" + Err.toString());
        }
The whole of this function it self is async.

Below is the function where I call the to insert details.

static insertDetails(SharedPreferences prefs, var response) async {     
    print("Token is :"+response['token']);
    print("userID is :"+response['userID']);    

    await prefs.setString(authTokenKey, response['token']);
        await prefs.setString(userIdKey, response['userID']);   

    }

我已经打印了令牌和用户 ID 不为空或为空。但我仍然收到“ setString ”的错误消息被调用为空。但它在仅适用于 Android 的 ios 上运行良好

只是补充一下,我在下面找到了这个。

接收方:null 尝试调用:setString("auth_token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTc2MDAzNTcsIMV4cCI6MTU1NzYwNjM1NywianRpIjoiNmExOE9CTE9m")

标签: iosfluttersharedpreferences

解决方案


insertDetails你传递一个nullfor prefs,所以当你尝试这样做时prefs.setString它会失败。

将您的 gitter 问题中的其他详细信息拼凑在一起,这是因为您传递的值尚未初始化(尚未)。

你有过于复杂的事情。你有一个成员变量

  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

那根本就没有做任何事情。SharedPreferences是一个单例,所以只要你需要它就获得一个参考是没有害处的。

另外值得注意的是,没有必要等待.setString()共享偏好的结果。新值会立即写入内存缓存,并将本机请求分派到 Android 或 iOS 层以将其提交到存储中。

像这样重构insertDetails

  static insertDetails(var response) async {
    print('Token is : ${response['token']}');
    print('userID is : ${response['userID']}');

    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(authTokenKey, response['token']);
    prefs.setString(userIdKey, response['userID']);
  }

推荐阅读