【问题标题】:How can i retrieve data from SharedPreferences and store it in a const?如何从 SharedPreferences 中检索数据并将其存储在 const 中?
【发布时间】:2021-08-23 21:27:35
【问题描述】:

我需要从 SharedPreferences 中获取一个数字并将其存储在一个常量中。但是我做不到。

SharedPreferences sp = await SharedPreferences.getInstance();
const int index = sp.getInt('index')!;

此代码抛出此错误:

Const variables must be initialized with a constant value.
Try changing the initializer to be a constant expression.

我想获取一次数据,以后不再更改。我怎样才能做到这一点?

【问题讨论】:

  • 你不能 const 在编译时应该是常量,并且从共享首选项中检索到的值在编译时是未知的。

标签: flutter dart constants flutter-sharedpreference


【解决方案1】:

将final 替换为const 和await,而不是等待instance。

SharedPreferences sp = SharedPreferences.getInstance();
final int index = await sp.getInt('index')!;

【讨论】:

  • 但如果我将其设为 final 而不是 const,我将无法在使用该数字的地方使用 const 小部件。我需要将小部件设为 const,以提高应用程序的性能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多