extension封装shared_preferences(简单好用)

Dart Extension 是指在 Dart 编程语言中使用的一种机制,它可以扩展现有类的功能,或者为一个类型添加新的方法和属性。通常情况下,Dart 中的扩展是通过关键字 extension 来定义的。需要注意的是,扩展方法只能访问原始对象的公共属性和方法,不能访问私有成员。

一、封装

import 'package:shared_preferences/shared_preferences.dart';

/// SharedPreferences封装
class SPrefsValue<T> {
  /// 缓存map
  static final _cacheMap = <String, Object?>{};

  /// 清除所有缓存
  static void cleanAllCache() {
    _cacheMap.clear();
  }

  /// 清除缓存
  static void removeCache(String key) {
    _cacheMap.remove(key);
  }

  /// key
  final String key;

  /// 默认值
  final T defaultValue;

  /// 是否缓存
  final bool hasCache;

  /// 初始化
  SPrefsValue(
    this.key,
    this.defaultValue, {
    this.hasCache = false,
  });

  /// 清除
  Future<bool> remove() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final state = await prefs.remove(key);
    _cacheMap.remove(key);
    return state;
  }

  /// 取值
  ///
  /// 如果设置使用缓存值,将优先使用缓存
  Future<T> getValue() async {
    try {
      // 缓存中取值
      if (hasCache && _cacheMap[key] != null && _cacheMap[key] is T) {
        return _cacheMap[key] as T;
      }
      final value = await _readValue() ?? defaultValue;

      // 更新缓存值
      if (hasCache && _cacheMap[key] != value) {
        _cacheMap[key] = value;
      }
      return value;
    } catch (e) {
      return defaultValue;
    }
  }

  /// 获取缓存中的值
  ///
  /// 为确保缓存有值,调用之前确认调用过set/getValue,
  T getCacheValue() {
    final cacheValue = _cacheMap[key];
    if (cacheValue != null && cacheValue is T) {
      return cacheValue as T;
    }
    return defaultValue;
  }

  /// 设置值
  Future<bool> setValue(T newValue) async {
    var state = false;
    try {
      if (hasCache) {
        _cacheMap[key] = newValue;
      }
      state = await _writeValue(value: newValue);
    } catch (e) {
      state = false;
    }
    return state;
  }

  /// 读取SharedPreferences存储值
  Future<T?> _readValue() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    T? value;
    if (T is int) {
      value = prefs.getInt(key) as T?;
    } else if (T is double) {
      value = prefs.getDouble(key) as T?;
    } else if (T is String) {
      value = prefs.getString(key) as T?;
    } else if (T is bool) {
      value = prefs.getBool(key) as T?;
    } else if (T is List<String>) {
      value = prefs.getStringList(key) as T?;
    } else {
      final listValue = prefs.get(key);
      if (listValue is List) {
        value = listValue.map((e) => e.toString()).toList() as T?;
      } else {
        value = prefs.get(key) as T?;
      }
    }

    return value;
  }

  /// 写入SharedPreferences存储值
  Future<bool> _writeValue({required T value}) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    var state = false;
    if (value is int) {
      state = await prefs.setInt(key, value);
    } else if (value is double) {
      state = await prefs.setDouble(key, value);
    } else if (value is String) {
      state = await prefs.setString(key, value);
    } else if (value is bool) {
      state = await prefs.setBool(key, value);
    } else if (value is List<String>) {
      state = await prefs.setStringList(key, value);
    }
    return state;
  }
}

/// 类型扩展
extension SPrefsData<T> on T {
  /// SharedPreferences扩展函数
  SPrefsValue<T> spValue(
    String valueKey, {
    T? defValue,
    bool hasCache = false,
  }) {
    return SPrefsValue(valueKey, defValue ?? this, hasCache: hasCache);
  }
}

二、使用


/// 本地存储工具
class SPrefsUtil {
  static final SPrefsUtil _instance = SPrefsUtil._();

  SPrefsUtil._();

  /// 工厂方法
  factory SPrefsUtil() {
    return _instance;
  }


  // 申明一个默认值为false的是否登录isLogin
  var isLogin = false.spValue('isLogin'); 
  // 申明一个默认值为空字符串的authToken
  var authToken = ''.spValue('Auth-Token', hasCache: true);
   
}



// 写入
SPrefsUtil().isLogin.setValue(true);
SPrefsUtil().authToken.setValue('123123');

  
// 读取
final loginSate = await SPrefsUtil().isLogin.getValue()
final token = await SPrefsUtil().authToken.getValue()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个使用 Flutter 操作 shared_preferences 的例程: ```dart import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; @override void initState() { super.initState(); _loadCounter(); } Future<void> _loadCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { _counter = (prefs.getInt('counter') ?? 0); }); } Future<void> _incrementCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { _counter++; prefs.setInt('counter', _counter); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Flutter Shared Preferences Demo"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } } ``` 这个例程演示了如何在 Flutter 中使用 shared_preferences 库来读取和写入应用程序的持久化数据。在这个例子中,我们使用一个整型变量 `_counter` 来记录用户点击按钮的次数。在 `initState` 方法中,我们调用 `_loadCounter` 方法来从 shared_preferences 中读取 `_counter` 的值。在 `_incrementCounter` 方法中,我们调用 `prefs.setInt('counter', _counter)` 来将 `_counter` 的值写入 shared_preferences。每当用户点击按钮时,我们调用 `_incrementCounter` 方法来增加 `_counter` 的值并更新 UI。 注意:为了使用 shared_preferences 库,你需要在 `pubspec.yaml` 文件中添加以下依赖项: ```yaml dependencies: shared_preferences: ^2.0.5 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值