简体   繁体   English

Flutter:共享偏好

[英]Flutter: shared preferences

I have this function:我有这个功能:

  Future<String> load(SharedPreferences prefs, String fileName) async {
    prefs = await SharedPreferences.getInstance();
    String jsonString = prefs.getString(fileName) ?? "";
    if (jsonString.isNotEmpty) {
      return jsonString;
    }else{
      return ...
    }
  }

What should I return in the else case?在 else 情况下我应该返回什么? I tried with "" but it doesn't work.我试过 "" 但它不起作用。

Shared Preferences共享偏好

In Flutter, Shared Preferences are used to store primitive data ( int , double , bool , string , and stringList ).在 Flutter 中,共享首选项用于存储原始数据( intdoubleboolstringstringList )。 This data is associated with the app, so when the user uninstalls your app, the data will also be deleted.此数据与应用程序相关联,因此当用户卸载您的应用程序时,数据也将被删除。

Get the plugin获取插件

The shared_preferences plugin from pub is a wrapper around Android SharedPreferences and iOS NSUserDefaults . pub 的shared_preferences插件是对 Android SharedPreferences和 iOS NSUserDefaults You can get this plugin by adding the shared_preferences line to your pubspec.yaml file in the dependencies section.您可以通过将shared_preferences行添加到依赖项部分的pubspec.yaml文件来获取此插件。

dependencies:
  shared_preferences: '>=0.5.12+2 <2.0.0'

You can change the version number to whatever the current one is, but anything less than 2.0 should be compatible.您可以将版本号更改为当前版本号,但任何低于 2.0 的版本都应该兼容。

Import the package导入包

In whichever file you need the Shared Preferences, add the following import:在您需要共享首选项的任何文件中,添加以下导入:

import 'package:shared_preferences/shared_preferences.dart';

Reading and writing data读取和写入数据

To get the shared preferences object you can do the following:要获取共享首选项对象,您可以执行以下操作:

final prefs = await SharedPreferences.getInstance();

This will be used for all of the following examples.这将用于以下所有示例。

int整数

  • read: final myInt = prefs.getInt('my_int_key') ?? 0;阅读: final myInt = prefs.getInt('my_int_key') ?? 0; final myInt = prefs.getInt('my_int_key') ?? 0;
  • write: prefs.setInt('my_int_key', 42);写: prefs.setInt('my_int_key', 42);

double双倍的

  • read: final myDouble = prefs.getDouble('my_double_key') ?? 0.0;阅读: final myDouble = prefs.getDouble('my_double_key') ?? 0.0; final myDouble = prefs.getDouble('my_double_key') ?? 0.0;
  • write: prefs.setDouble('my_double_key', 3.14);写: prefs.setDouble('my_double_key', 3.14);

bool布尔值

  • read: final myBool = prefs.getBool('my_bool_key') ?? false;阅读: final myBool = prefs.getBool('my_bool_key') ?? false; final myBool = prefs.getBool('my_bool_key') ?? false;
  • write: prefs.setBool('my_bool_key', true);写: prefs.setBool('my_bool_key', true);

string细绳

  • read: final myString = prefs.getString('my_string_key') ?? '';阅读: final myString = prefs.getString('my_string_key') ?? ''; final myString = prefs.getString('my_string_key') ?? '';
  • write: prefs.setString('my_string_key', 'hello');写: prefs.setString('my_string_key', 'hello');

stringList字符串列表

  • read: final myStringList = prefs.getStringList('my_string_list_key') ?? [];阅读: final myStringList = prefs.getStringList('my_string_list_key') ?? []; final myStringList = prefs.getStringList('my_string_list_key') ?? [];
  • write: prefs.setStringList('my_string_list_key', ['horse', 'cow', 'sheep']);写: prefs.setStringList('my_string_list_key', ['horse', 'cow', 'sheep']);

Removing data删除数据

You can remove any saved data by supplying the key name:您可以通过提供密钥名称来删除任何保存的数据:

prefs.remove('my_int_key');

I rarely find a need to do that, though.不过,我很少觉得有必要这样做。 I just overwrite the old data or ignore it.我只是覆盖旧数据或忽略它。 You shouldn't store any sensitive data in Shared Preferences.您不应在共享首选项中存储任何敏感数据。

See also也可以看看

The answer is "it depends".答案是“视情况而定”。 Namely, it depends on what exactly you are doing with the result of this function, and what a good empty default value means in that context.也就是说,这取决于您对这个函数的结果到底做了什么,以及在该上下文中一个好的空默认值意味着什么。

Assuming you're decoding the returned JSON string into a Map<String, dynamic> , then a good default value might be the empty map.假设您将返回的 JSON 字符串解码Map<String, dynamic> ,那么一个好的默认值可能是空映射。 In that case, you could reformulate your function as follows:在这种情况下,您可以按如下方式重新构造函数:

Future<String> loadJSON(final String fileName) async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final String jsonString = prefs.getString(fileName);
  if (jsonString != null && jsonString.isNotEmpty) {
    return jsonString;
  }
  return "{}"; // default value
}

final String jsonString = await loadJSON("test.json");

final Map<String, dynamic> jsonData = json.decode(jsonString);

However, it probably makes more sense to reformulate this procedure as a slightly higher-level function returning actual map values:然而,将这个过程重新表述为一个返回实际地图值的稍微高级的函数可能更有意义:

Future<Map<String, dynamic>> loadData(final String fileName) async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final String jsonString = prefs.getString(fileName);
  if (jsonString != null && jsonString.isNotEmpty) {
    return json.decode(jsonString);
  }
  return Map(); // default value
}

final Map<String, dynamic> jsonData = await loadData("test.json");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM