【问题标题】:how to check if SharedPreferences file existed or not in flutter如何在颤动中检查 SharedPreferences 文件是否存在
【发布时间】:2022-01-21 22:10:11
【问题描述】:

我的 Flutter 应用程序需要在我的应用程序开始时检查是否有 SharedPreferences 文件以及 SharedPreferences 中是否有值。

这是我的代码:

最后它会产生以下错误

【问题讨论】:

  • 请将代码和错误发布为文本,而不是图像。另外,await getShredPrefs(); 呢?

标签: flutter flutter-sharedpreference


【解决方案1】:

就像 cmets 中提到的那样,拥有带有代码的图像非常烦人,因为您无法复制自己尝试其中的一些。尝试在您的问题中获取实际代码:)

通常它应该已经工作,如果文件不存在,则生成文件。

// the below code is in an async function
final SharedPreferences prefs = await SharedPreferences.getInstance();

// the value of name can be null, so it's of type String?
final String? name = prefs.getString('name');

// the value of job cannot be null, as a default is given
// ?? ensures that if the left side is null, the default value 'jobless' is assigned
final String job = prefs.getString('job') ?? 'jobless';

修改此代码应该适用于您的情况

【讨论】:

    猜你喜欢
    • 2011-10-21
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多