我有我的 flutter 应用程序,登录时我调用共享首选项来存储一些值,例如 token 、用户 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']);
}
我已经打印了 token 和用户 ID 都不为空或为空。但我仍然收到错误消息 'setString' was called on null。但它在 Android only ios 上工作得很好
补充一下,我在下面找到了这个。
Receiver: null Tried calling: setString("auth_token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTc2MDAzNTcsImV4cCI6MTU1NzYwNjM1NywianRpIjoiNmExOE9CTE9m")
最佳答案
在 insertDetails 中,您正在为 prefs 传递一个 null,因此当您尝试执行 prefs.setString 它失败了。
将您的 gitter 问题中的其他详细信息拼凑在一起,这是因为您传递的值尚未初始化(尚未)。
你的事情太复杂了。你有一个成员变量
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
那根本就是什么都没做。 SharedPreferences 是单例,因此只要在需要时获取引用就没什么坏处。
还需要注意的是,不必等待 .setString() 对共享首选项的结果。新值会立即写入内存缓存,并向 Android 或 iOS 层发送 native 请求以将其提交到存储。
像这样重构 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']);
}
关于ios - Flutter ios shared preference show setstring on null 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093051/