如何创建可在 flutter 的完整项目中使用的共享首选项的单个实例

Pri*_*wal 8 android single-instance sharedpreferences dart flutter

每当我们必须使用共享首选项时,我们都必须创建它的一个实例。

在 flutter 中,创建共享首选项的实例是异步的;

final prefs = await SharedPreferences.getInstance();

每当我们必须像上面那样使用它时,我们都必须始终创建它的实例。

有没有一种方法可以创建共享首选项的单个实例,该实例可供整个项目使用,而我们不必在 Flutter 中一次又一次地创建其实例?

Ham*_*yev 8

创建 Singleton 类SharedPreference

将此类放入项目中
       import 'dart:async' show Future;
       import 'package:shared_preferences/shared_preferences.dart';
    
       class PreferenceUtils {
         static Future<SharedPreferences> get _instance async => _prefsInstance ??= await SharedPreferences.getInstance();
         static SharedPreferences _prefsInstance;
        
         // call this method from iniState() function of mainApp().
         static Future<SharedPreferences> init() async {
           _prefsInstance = await _instance;
           return _prefsInstance;
         }
       
         static String getString(String key, [String defValue]) {
           return _prefsInstance.getString(key) ?? defValue ?? "";
         }
       
         static Future<bool> setString(String key, String value) async {
           var prefs = await _instance;
           return prefs?.setString(key, value) ?? Future.value(false);
         }
       }
Run Code Online (Sandbox Code Playgroud)
在 initState() 主类中初始化该类
 void main() async {
  // Required for async calls in `main`
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize PreferenceUtils instance.
  await PreferenceUtils.init();

  runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)
在方法中访问
PreferenceUtils.setString(AppConstants.USER_ID, "");
String userId = PreferenceUtils.getString(AppConstants.USER_ID);
Run Code Online (Sandbox Code Playgroud)

更多: https: //dev.to/lucianojung/flutter-singelton-pattern-1a38