ios - 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")
解决方案
在insertDetails
你传递一个null
for 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']);
}
推荐阅读
- fwrite - fwrite() 大文件大小损坏,我需要脚本帮助
- html - 谁使用 Canvas API 绘制和填充两条略微偏移的曲线
- vue.js - 在鼠标悬停时更改 :src
- python - 使用 Selenium 和 Python 在连接超时时使用 while 循环从头开始
- javascript - 将键分配给 JSON 对象
- javascript - 具有依赖关系的多个调用 redux-thunk
- javascript - 为什么我们创建一个变量来引用一个类而不是仅仅使用 document.querySelector(".class")?
- excel - 使用大文本填充 Word 文档
- java - 如何打印出数组索引 2-5
- python - 如何从用户输入的字符串中删除引号并将其用于其他目的?