【问题标题】:Flutter ios shared preference show setstring on null errorFlutter ios 共享首选项显示 setstring on null 错误
【发布时间】:2023-03-23 18:23:01
【问题描述】:

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

这里是代码sn-p。

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' 的错误消息在 null 上被调用。但它在仅适用于 Android 的 ios 上运行良好

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

Receiver: null 尝试调用:setString("auth_token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTc2MDAzNTcsImV4cCI6MTU1NzYwNjM1NywianRpIjoiNmExOE9CTE9m")

【问题讨论】:

  • 您在 gitter 上提出了同样的问题,并在那里提供了更多详细信息。如果没有这些细节,就很难按照书面形式回答这个问题。请随时使用其他相关详细信息更新您的问题。
  • @RichardHeap 很抱歉我在这里缺少信息,但现在我收到了一个新错误,如下所示,我已在您的回答中添加了评论

标签: ios flutter sharedpreferences


【解决方案1】:

insertDetails 中,您正在为prefs 传递null,因此当您尝试执行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']);
  }

【讨论】:

  • 感谢您的帮助。现在我已经尝试过你这样的方法 await AuthUtils.insertDetails(responseJson);但我最终得到一个新错误,即 MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
  • 我应该为这个问题将这个错误提交到 github 吗?
  • 这很奇怪。包括我在内的数以千计的应用程序运行良好,但没有显示出来。它不太可能是一个错误。在报告之前尝试克隆源代码库并运行示例应用程序。
  • 是的,这很奇怪,您知道它在具有相同代码的 Android 上运行良好。令您惊讶的是,我做了一个新项目,然后手动复制了我的代码,现在带有我的代码的新项目运行良好,没有任何问题。
  • 很高兴你成功了——如果答案有用,别忘了接受它——谢谢
猜你喜欢
  • 2018-10-03
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 2019-03-08
  • 2021-03-30
相关资源
最近更新 更多