Flutter共享偏好返回NULL

m0rkklqb  于 2023-01-27  发布在  Flutter
关注(0)|答案(3)|浏览(109)

我还有下一段flutter代码,用于获取共享偏好键-值
我确实理解为什么**_blueUriInit**始终为NULL

mwngjboj

mwngjboj1#

我假设您在调用获取其值之前忘记为该键提供值,您需要先为其赋值:

Future<bool> saveData(String key, dynamic value) async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.setString(key, value);
}

这样称呼它:

void initState() {
   saveData('blueUri', 'test');

   setState(() {
     _blueUriInit = getValue('blueUri');
   });
   super.initState();
}

现在,下次打开应用时,getValue应返回test

toiithl6

toiithl62#

可以创建此函数来设置值

static setUserID(String key, String value) async {
   final SharedPreferences preferences = await SharedPreferences.getInstance();
   preferences.setString(key, value);
}

使用案例:

await SharedValue.setUserID("Email", "demo@gmail.com");

要从共享首选项获取值,可以使用以下函数

static Future<String?> getUserID(String key) async {
    final SharedPreferences preferences = await SharedPreferences.getInstance();
    return preferences.getString(key);
}

使用案例:

userName = await SharedValue.getUserID("Email");
pgpifvop

pgpifvop3#

首先,需要使用键和值设置字符串(name是键)

Future setValue() async {
  final prefs = await SharedPreferences.getInstance();
  prefs.setString("name", "Hitarth");
}

getString with key(这里我把“name”作为键)

Future getValue(String key) async {
  final prefs = await SharedPreferences.getInstance();
  String value = prefs.getString(key) ?? "NULL";
  return value;
}

存储在调用getValue变量中

void initState() {
  setState(() {
    _blueUriInit = getValue("name");
  });
  super.initState();
}

相关问题