Flutter支持Preferences(Shared Preferences and NSUserDefaults) 、文件、和Sqlite3。若想使用这个功能需要引入官方仓库的相应插件,下面详细介绍这三种存储方式的使用方法。

Preferences

https://pub.dev/packages/shared_preferences

Flutter官方推荐我们用shared_preferences进行数据存储,它类似于React Native中的AsyncStorage

什么是shared_preferences?

shared_preferences是Flutter社区开发的一个本地数据存取插件,它有以下特性:

  • 简单的,异步的,持久化的key-value存储系统;
  • 在Android上它是基于SharedPreferences的;
  • 在iOS上它是基于NSUserDefaults的;

如何使用shared_preferences?

安装依赖
  1. dependencies:
  2. shared_preferences: ^0.5.12+4

导入
  1. import 'package:shared_preferences/shared_preferences.dart';

基本使用
  1. _onClick() async {
  2. SharedPreferences prefs = await SharedPreferences.getInstance();
  3. // 设置缓存
  4. prefs.setString(book, '飘');
  5. Map m1 = {
  6. 'name': 'jack',
  7. 'age': 18,
  8. };
  9. prefs.setString(mapJson, json.encode(m1));
  10. // 获取缓存
  11. print(prefs.get(book)); //飘
  12. print(prefs.getString(book)); //飘
  13. print(json.decode(prefs.get(mapJson))); //{name: jack, age: 18}
  14. //移除指定key的缓存
  15. prefs.remove(book);
  16. //清除所有缓存
  17. prefs.clear();
  18. }

封装1

/lib/utils/storage.dart

  1. import 'dart:convert';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. /// 存储封装
  4. /// 该封装 key 只允许为 String 类型,如果需要其他类型,需直接使用 SharedPreferences 相关方法。
  5. /// value 只允许为 String 类型。其他类型需要先转为String,再进行存储;如需直接存储其他类型数据,请直接使用 SharedPreferences 相关方法。
  6. class ZqStorage {
  7. SharedPreferences prefs;
  8. // 单例模式
  9. static var _instance = ZqStorage._internal();
  10. static getInstance() => _instance._createPrefs();
  11. ZqStorage._internal() {}
  12. // 创建 SharedPreferences 实例
  13. _createPrefs() async {
  14. if (prefs == null) {
  15. prefs = await SharedPreferences.getInstance();
  16. }
  17. return this;
  18. }
  19. // 设置
  20. set(String key, value) {
  21. // 不管value为 什么类型,全部转为 String 类型
  22. prefs.setString(key, json.encode(value));
  23. }
  24. // 获取
  25. get(String key, [bool decode = false]) {
  26. var value = prefs.get(key);
  27. if (value != null) {
  28. if (decode) return json.decode(value);
  29. return value;
  30. }
  31. return null;
  32. }
  33. // 是否包含
  34. has(String key) => prefs.containsKey(key);
  35. // 清除指定
  36. remove(String key) {
  37. prefs.remove(key);
  38. }
  39. // 清除所有
  40. clear() {
  41. prefs.clear();
  42. }
  43. }
  1. import 'package:app1/utils/storage.dart';
  2. _onClick() async {
  3. var s1 = await ZqStorage.getInstance();
  4. s1.set('username', {'name': 'jack', 'age': 18});
  5. print( s1.get('username') ); //String {"name": "jack", "age": "18"}
  6. print( s1.get('username', true) ); //Map {name: jack, age: 18}
  7. s1.set('isLogin', 'true');
  8. print( s1.get('isLogin') ); //String "true"
  9. print( s1.get('isLogin', true) ); //bool true
  10. s1.set('unread_notice', 1);
  11. print( s1.get('unread_notice') ); //String "1"
  12. print( s1.get('unread_notice2', true) ); //int 1
  13. s1.set('list', [1, 2, 3]);
  14. print( s1.get('list') ); //String "[1, 2, 3]"
  15. print( s1.get('list', true) ); //List [1, 2, 3]
  16. }

文件存储

导入插件
  1. 打开项目的pubspec.yaml配置,在dependencies节点下新增配置:
    path_provider: ^0.4.0
  2. 点击开发工具提示的packages get按钮或者在命令行输入flutter packages get来同步第三方插件
  3. 在Dart文件中引入插件
    import 'package:path_provider/path_provider.dart';

    使用示例

    获取文件路径方法:

  4. 获取应用缓存目录: getTemporaryDirectory

    • 类似iOS的NSTemporaryDirectory和Android的getCacheDir
  5. 获取应用文件目录: getApplicationDocumentsDirectory
    • 类似iOS的NSDocumentDirectory和Android上的AppData目录
    • 应用程序被删除时,系统会清除目录
  6. 存储卡: getExternalStorageDirectory
    • 仅支持Android平台
  1. // 找到正确的本地路径
  2. Future<String> get _localPath async {
  3. final directory = await getApplicationDocumentsDirectory();
  4. return directory.path;
  5. }
  6. // 创建对文件位置的引用
  7. Future<File> get _localFile async {
  8. final path = await _localPath;
  9. return new File('$path/counter.txt');
  10. }
  11. // 将数据写入文件
  12. Future<File> writeCounter(int counter) async {
  13. final file = await _localFile;
  14. // Write the file
  15. return file.writeAsString('$counter');
  16. }
  17. // 从文件中读取数据
  18. Future<int> readCounter() async {
  19. try {
  20. final file = await _localFile;
  21. // Read the file
  22. String contents = await file.readAsString();
  23. return int.parse(contents);
  24. } catch (e) {
  25. // If we encounter an error, return 0
  26. return 0;
  27. }
  28. }

Sqfite

SQLite plugin for Flutter. Get the default databases location. On Android, it is typically data/data//databases, On iOS, it is the Documents directory.

导入插件
  1. 打开项目的pubspec.yaml配置,在dependencies节点下新增配置:
    sqflite: ^1.0.0
  2. 点击开发工具提示的packages get按钮或者在命令行输入flutter packages get来同步第三方插件
  3. 在Dart文件中引入插件
    import 'package:sqflite/sqflite.dart';

    使用示例

  1. // 获取数据库文件的存储路径
  2. var databasesPath = await getDatabasesPath();
  3. String path = join(databasesPath, 'demo.db');
  4. // 创建数据库表
  5. db = await openDatabase(path, version: 1,
  6. onCreate: (Database db, int version) async {
  7. await db.execute('''
  8. CREATE TABLE $tableBook (
  9. $columnId INTEGER PRIMARY KEY,
  10. $columnName TEXT,
  11. $columnAuthor TEXT,
  12. $columnPrice REAL,
  13. $columnPublishingHouse TEXT)
  14. ''');
  15. });
  16. // 插入数据
  17. Future<int> rawInsert(String sql, [List<dynamic> arguments]);
  18. Future<int> insert(String table, Map<String, dynamic> values,
  19. {String nullColumnHack, ConflictAlgorithm conflictAlgorithm});
  20. // 查询数据
  21. Future<List<Map<String, dynamic>>> rawQuery(String sql,
  22. [List<dynamic> arguments]);
  23. Future<List<Map<String, dynamic>>> query(String table,
  24. {bool distinct,
  25. List<String> columns,
  26. String where,
  27. List<dynamic> whereArgs,
  28. String groupBy,
  29. String having,
  30. String orderBy,
  31. int limit,
  32. int offset});
  33. // 更新数据
  34. Future<int> rawUpdate(String sql, [List<dynamic> arguments]);
  35. Future<int> update(String table, Map<String, dynamic> values,
  36. {String where,
  37. List<dynamic> whereArgs,
  38. ConflictAlgorithm conflictAlgorithm});
  39. // 删除
  40. Future<int> rawDelete(String sql, [List<dynamic> arguments]);
  41. Future<int> delete(String table, {String where, List<dynamic> whereArgs});
  42. // 关闭数据库
  43. Future close() async => db.close();