Flutter-轻量级数据存储-SharedPreferences

轻量级数据存储-SharedPreferences

  • 依赖
  • 简单使用
    • 保存/读取数据
  • 封装
    • 代码
    • 使用
  • 实战
    • 效果图
    • 代码

依赖

shared_preferences: ^2.0.13

简单使用

保存/读取数据

shared_preferences 支持的数据类型有 int、double、bool、string、stringList。

  //保存数据
  static Future<bool> setString(String key, String? value,
      [String defaultValue = '']) async {
    var sp = await SharedPreferences.getInstance();
    return sp.setString(key, value ?? defaultValue);
  }

  //获取数据
  static Future<String> getString(String key,
      [String defaultValue = 'false']) async {
    var sp = await SharedPreferences.getInstance();
    return sp.getString(key) ?? defaultValue;
  }

封装

代码

import 'package:shared_preferences/shared_preferences.dart';

class SpUtils {
  static void setValue(String key, Object? value) {
    if (value is int) {
      setInt(key, value);
    } else if (value is bool) {
      setBool(key, value);
    } else if (value is double) {
      setDouble(key, value);
    } else if (value is String) {
      setString(key, value);
    } else if (value is List<String>) {
      setStringList(key, value);
    }
  }

  static Future getValue<T>(String key, T defaultValue) async {
    if (defaultValue is int) {
      return getInt(key, defaultValue);
    } else if (defaultValue is double) {
      return getDouble(key, defaultValue);
    } else if (defaultValue is bool) {
      return getBool(key, defaultValue);
    } else if (defaultValue is String) {
      return getString(key, defaultValue);
    } else if (defaultValue is List<String>) {
      return getStringList(key);
    }
  }

  static void setInt(String key, int? value, [int defaultValue = 0]) async {
    var sp = await SharedPreferences.getInstance();
    sp.setInt(key, value ?? defaultValue);
  }

  static Future<int> getInt(String key, [int defaultValue = 0]) async {
    var sp = await SharedPreferences.getInstance();
    return sp.getInt(key) ?? defaultValue;
  }

  static Future<bool> setBool(String key, bool? value,
      [bool defaultValue = false]) async {
    var sp = await SharedPreferences.getInstance();
    return sp.setBool(key, value ?? defaultValue);
  }

  static Future<bool> getBool(String key, [bool defaultValue = false]) async {
    var sp = await SharedPreferences.getInstance();
    return sp.getBool(key) ?? defaultValue;
  }

  static Future<bool> setDouble(String key, double? value,
      [double defaultValue = 0.0]) async {
    var sp = await SharedPreferences.getInstance();
    return sp.setDouble(key, value ?? defaultValue);
  }

  static Future<double> getDouble(String key,
      [double defaultValue = 0.0]) async {
    var sp = await SharedPreferences.getInstance();
    return sp.getDouble(key) ?? defaultValue;
  }

  static Future<bool> setString(String key, String? value,
      [String defaultValue = '']) async {
    var sp = await SharedPreferences.getInstance();
    return sp.setString(key, value ?? defaultValue);
  }

  static Future<String> getString(String key,
      [String defaultValue = 'false']) async {
    var sp = await SharedPreferences.getInstance();
    return sp.getString(key) ?? defaultValue;
  }

  static Future<bool> setStringList(String key, List<String> value) async {
    var sp = await SharedPreferences.getInstance();
    return sp.setStringList(key, value);
  }

  static Future<List<String>> getStringList(String key) async {
    var sp = await SharedPreferences.getInstance();
    return sp.getStringList(key) ?? List.empty();
  }

  static Future<bool> remove(String key) async {
    var sp = await SharedPreferences.getInstance();
    return sp.remove(key);
  }

  static Future<bool> clearAll() async {
    var sp = await SharedPreferences.getInstance();
    return sp.clear();
  }

  static Future<Set<String>> getKeys() async {
    var sp = await SharedPreferences.getInstance();
    return sp.getKeys();
  }

  static Future<bool> containsKey(String key) async {
    var sp = await SharedPreferences.getInstance();
    return sp.containsKey(key);
  }
}

使用

SpUtils.setBool(key,false)

SPUtils.getBool(key)

实战

效果图

Flutter-轻量级数据存储-SharedPreferences_第1张图片

代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'sp_utils.dart';

void main() => runApp(const MaterialApp(home: HomePage()));

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: InkWell(
            child: const Icon(Icons.arrow_back),
            onTap: () => SystemNavigator.pop()),
        title: const Text('设置',
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
      ),
      body: Column(
        children: [
          _SettingItem(
            title: '查看通讯录好友',
            subTitle: '开启后,他人也可以从通讯录中发现我的知乎账号',
            itemBean: SettingItemBean(key: 'key1'),
          ),
          const Divider(),
          _SettingItem(
            title: '水印图片',
            subTitle: '在上传的图片添加水印',
            itemBean: SettingItemBean(key: 'key2'),
          ),
          const Divider(),
          _SettingItem(
            title: '内置音效',
            subTitle: '应用内按钮点击音效',
            itemBean: SettingItemBean(key: 'key3'),
          ),
          const Divider(),
          _SettingItem(
            title: '视频自动播放',
            subTitle: '移动流量和WIFI',
            itemBean: SettingItemBean(isArrow: true),
          ),
          const Divider(),
          _SettingItem(
            title: '消息设置',
            itemBean: SettingItemBean(isArrow: true),
          ),
          const Divider(),
        ],
      ),
    );
  }
}

class _SettingItem extends StatefulWidget {
  final String title;
  final String? subTitle;

  final SettingItemBean itemBean;

  const _SettingItem(
      {Key? key, required this.title, this.subTitle, required this.itemBean})
      : super(key: key);

  @override
  _SettingItemState createState() => _SettingItemState();
}

class _SettingItemState extends State<_SettingItem> {

  _checkItem() {
    return FutureBuilder(
      future: SpUtils.getBool(widget.itemBean.key),
      initialData: widget.itemBean.init,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) =>
          CupertinoSwitch(
              activeColor: Colors.blue,
              value: snapshot.data ?? widget.itemBean.init,
              onChanged: (checked) {
                setState(() {});
                SpUtils.setBool(widget.itemBean.key, checked);
              }),
    );
  }

  _arrowRightItem() {
    return const Padding(
        padding: EdgeInsets.symmetric(horizontal: 10),
        child: Icon(Icons.keyboard_arrow_right));
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        widget.title,
        style: const TextStyle(fontSize: 16),
      ),
      subtitle: widget.subTitle == null
          ? null
          : Text(widget.title, style: const TextStyle(fontSize: 13)),
      trailing: widget.itemBean.isArrow ? _arrowRightItem() : _checkItem(),
    );
  }
}

class SettingItemBean {
  bool init;
  String key;
  bool isArrow;

  SettingItemBean({this.init = false, this.key = '', this.isArrow = false});
}

你可能感兴趣的:(Flutter,flutter,存储,sp)