Flutter SharedPreferences 最佳实践

202 阅读2分钟

本方案废弃⚠️

在使用SharedPreferences时,控制台出现如下错误提示。

Android : Couldn't create directory for SharedPreferences file

这是因为项目中已经创建SharedPreferences实例。

解决方案:

import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesService {
  // Private constructor
  // The private constructor is defined to ensure that an instance of the class cannot be created from outside the class.
  SharedPreferencesService._internal();
  // Singleton instance
  // The static _instance variable is defined as an instance of the SharedPreferencesService class. This is the singleton instance that will be used throughout the app.
  static final SharedPreferencesService _instance = SharedPreferencesService._internal();
  // Getter for the instance
  // The static getter method is defined to return the singleton instance for use in other parts of the app.
  static SharedPreferencesService get instance => _instance;
  // SharedPreferences instance variable
  // The _preferences variable is defined as an instance of the SharedPreferences class. This variable will hold the shared preferences data.
  late SharedPreferences _preferences;
  // Initializes the SharedPreferences instance variable
  // The init method is defined to initialize the _preferences variable by calling the SharedPreferences.getInstance() method. Since this method is asynchronous, the init method is also marked as asynchronous using the Future<void> return type.
  Future<void> init() async {
    _preferences = await SharedPreferences.getInstance();
  }

  // Getters and Setters for SharedPreferences values
  // The getters and setters for SharedPreferences values are defined, but they are commented out because they are not necessary for the code's purpose. These methods would allow other parts of the app to retrieve and modify shared preferences data using methods like getString and setString.
  String? getString(String key) => _preferences.getString(key);
  Future<bool> setString(String key, String value) =>
      _preferences.setString(key, value);
  int? getInt(String key) => _preferences.getInt(key);
  Future<bool> setInt(String key, int value) =>
      _preferences.setInt(key, value);
  bool? getBool(String key) => _preferences.getBool(key);
  Future<bool> setBool(String key, bool value) =>
      _preferences.setBool(key, value);
  Future<bool> remove(String key) => _preferences.remove(key);
}

上面代码是对SharedPreferences的封装。

这个类的目的是创建一个单例模式的 SharedPreferences 实例,以便在整个应用程序中共享同一个实例。它使用了私有构造函数和静态变量来实现单例模式。

同时提供了一系列方法来获取和设置SharedPreferences中的值,例如获取字符串( getString )、设置字符串( setString )、获取整数( getInt )、设置整数( setInt )、获取布尔值( getBool )、设置布尔值( setBool )等。

通过使用单例模式,可以确保只有一个实例存在,避免多个实例之间的数据冲突和不一致性,这样就解决了上面的错误提示。