Flutter 數(shù)據(jù)存儲

最近開始著手做Flutter的項目,研究了一下Flutter的數(shù)據(jù)存儲。
Flutter支持PreferencesShared PreferencesNSUserDefaults) 、文件和Sqflite。使用時需要引入官方倉庫的一些相應(yīng)依賴,下面詳細介紹這三種存儲方式的使用方法。

一、Preferences:(相當于iOS的NSUserDefaults和Android的SharedPreferences

依賴導入步驟:

1)在pubspec.yaml文件下添加:

 # 添加sharedPreference依賴
 shared_preferences: ^0.5.0

2)點擊pubspec.yaml文件右上角的“Packages get”按鈕或者在當前pubspec.yaml文件目錄下在終端中輸入“flutter packages get”來同步該依賴。

3)在使用的Dart文件中引入依賴的頭文件即可使用:

import 'package:shared_preferences/shared_preferences.dart';
pubspec.yaml文件中添加依賴方式如下圖:
添加依賴

直接上代碼:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 創(chuàng)建一個新路由
class shared_preferences_Route extends StatefulWidget {
  @override // 重寫
  State<StatefulWidget> createState() => StorageState();
}

class StorageState extends State {
  var _textFieldController = new TextEditingController();
  var _storageString = '';
  final STORAGE_KEY = 'storage_key';

  /**
   * 利用SharedPreferences存儲數(shù)據(jù)
   */
  Future saveString() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString(
        STORAGE_KEY, _textFieldController.value.text.toString());
  }

  /**
   * 獲取存在SharedPreferences中的數(shù)據(jù)
   */
  Future getString() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    setState(() {
      _storageString = sharedPreferences.get(STORAGE_KEY);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Shared Preferences存儲'),
      ),
      body: new Column(
        children: <Widget>[
          Text("請輸入文本", textAlign: TextAlign.center),
          TextField(
            controller: _textFieldController,
          ),
          MaterialButton(
            onPressed: saveString,
            child: new Text("存儲"),
            color: Colors.pink,
          ),
          MaterialButton(
            onPressed: getString,
            child: new Text("獲取"),
            color: Colors.lightGreen,
          ),
          Text('shared_preferences存儲的值為  $_storageString'),


        ],
      ),
    );
  }
}

plist文件中存儲的數(shù)據(jù)如下圖:

plist文件路徑

存儲內(nèi)容展示:

preferences存儲

二、文件存儲:

文件存儲依賴導入方式和Preferences的依賴導入是一樣的。依賴如下:

# 添加文件依賴
path_provider: ^0.5.0

在 Flutter 里實現(xiàn)文件讀寫,需要使用 path_providerdartio 模塊。path_provider 負責查找iOS/Android 的目錄文件,IO 模塊負責對文件進行讀寫。引用的頭文件如下:

import 'package:path_provider/path_provider.dart';
import 'dart:io';
path_provider中有三個獲取文件路徑的方法:
  • getTemporaryDirectory() //獲取應(yīng)用緩存目錄,等同iOS的NSTemporaryDirectory()和Android的getCacheDir() 方法。
  • getApplicationDocumentsDirectory() //獲取應(yīng)用文件目錄類似于iOS的NSDocumentDirectory和Android上的 AppData目錄。
  • getExternalStorageDirectory() //這個是存儲卡,僅僅在Android平臺可以使用。

直接上代碼:

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

// 創(chuàng)建一個新路由
class file_Route extends StatefulWidget {
  @override // 重寫
  State<StatefulWidget> createState() => StorageState();
}

class StorageState extends State {
  var _textFieldController = new TextEditingController();
  var _storageString = '';

  /**
   * 利用文件存儲數(shù)據(jù)
   */
  saveString() async {
    final file = await getFile('file.text');
    //寫入字符串
    file.writeAsString(_textFieldController.value.text.toString());
  }

  /**
   * 獲取存在文件中的數(shù)據(jù)
   */
  Future getString() async {
    final file = await getFile('file.text');
    var filePath  = file.path;
    setState(() {
      file.readAsString().then((String value) {
        _storageString = value +'\n文件存儲路徑:'+filePath;
      });
    });
  }

  /**
   * 初始化文件路徑
   */
  Future<File> getFile(String fileName) async {
    //獲取應(yīng)用文件目錄類似于Ios的NSDocumentDirectory和Android上的 AppData目錄
    final fileDirectory = await getApplicationDocumentsDirectory();

    //獲取存儲路徑
    final filePath = fileDirectory.path;

    //或者file對象(操作文件記得導入import 'dart:io')
    return new File(filePath + "/"+fileName);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('文件存儲'),
      ),
      body: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("文件存儲", textAlign: TextAlign.center),
          TextField(
            controller: _textFieldController,
          ),
          MaterialButton(
            onPressed: saveString,
            child: new Text("存儲"),
            color: Colors.cyan,
          ),
          MaterialButton(
            onPressed: getString,
            child: new Text("獲取"),
            color: Colors.deepOrange,
          ),
          Text('從文件存儲中獲取的值為  $_storageString'),
        ],
      ),
    );
  }
}

存儲內(nèi)容展示:

文件存儲

三、Sqflite 數(shù)據(jù)庫存儲

官方說明:

SQLite plugin for Flutter. Supports both iOS and Android.

 Support transactions and batches
 Automatic version managment during open
 Helpers for insert/query/update/delete queries
 DB operation executed in a background thread on iOS and Android

意思是:Sqflite是一個同時支持Android跟iOS平臺的數(shù)據(jù)庫,并且支持標準的CURD操作。
使用時同樣需要引入依賴:

#添加Sqflite依賴
sqflite: ^1.0.0

引入頭文件:

import 'package:sqflite/sqflite.dart';

簡單使用代碼如下:

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class Sqflite_Route extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => StorageState();
}

class StorageState extends State {
  var _textFieldController = new TextEditingController();
  var _storageString = '';

  /**
   * 利用Sqflite數(shù)據(jù)庫存儲數(shù)據(jù)
   */
  saveString() async {
    final db = await getDataBase('my_db.db');
    //寫入字符串
    db.transaction((trx) {
      trx.rawInsert(
          'INSERT INTO user(name) VALUES("${_textFieldController.value.text.toString()}")');
    });
  }

  /**
   * 獲取存在Sqflite數(shù)據(jù)庫中的數(shù)據(jù)
   */
  Future getString() async {
    final db = await getDataBase('my_db.db');
    var dbPath = db.path;
    setState(() {
      db.rawQuery('SELECT * FROM user').then((List<Map> lists) {
        print('----------------$lists');
        var listSize = lists.length;
        //獲取數(shù)據(jù)庫中的最后一條數(shù)據(jù)
        _storageString = lists[listSize - 1]['name'] +
            "\n現(xiàn)在數(shù)據(jù)庫中一共有${listSize}條數(shù)據(jù)" +
            "\n數(shù)據(jù)庫的存儲路徑為${dbPath}";
      });
    });
  }

  /**
   * 初始化數(shù)據(jù)庫存儲路徑
   */
  Future<Database> getDataBase(String dbName) async {
    //獲取應(yīng)用文件目錄類似于Ios的NSDocumentDirectory和Android上的 AppData目錄
    final fileDirectory = await getApplicationDocumentsDirectory();

    //獲取存儲路徑
    final dbPath = fileDirectory.path;

    //構(gòu)建數(shù)據(jù)庫對象
    Database database = await openDatabase(dbPath + "/" + dbName, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute("CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT)");
        });

    return database;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('數(shù)據(jù)存儲'),
      ),
      body: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("Sqflite數(shù)據(jù)庫存儲", textAlign: TextAlign.center),
          TextField(
            controller: _textFieldController,
          ),
          MaterialButton(
            onPressed: saveString,
            child: new Text("存儲"),
            color: Colors.cyan,
          ),
          MaterialButton(
            onPressed: getString,
            child: new Text("獲取"),
            color: Colors.deepOrange,
          ),
          Text('從Sqflite數(shù)據(jù)庫中獲取的值為  $_storageString'),
        ],
      ),
    );
  }
}

數(shù)據(jù)庫展示:

sqflite數(shù)據(jù)庫存儲

其他方法:創(chuàng)建數(shù)據(jù)庫、增刪改查等方法如下:

// 獲取數(shù)據(jù)庫文件的存儲路徑
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');

// 創(chuàng)建數(shù)據(jù)庫表
db = await openDatabase(path, version: 1,
       onCreate: (Database db, int version) async {
   await db.execute('''
        CREATE TABLE $tableBook (
            $columnId INTEGER PRIMARY KEY, 
            $columnName TEXT, 
            $columnAuthor TEXT, 
            $columnPrice REAL, 
            $columnPublishingHouse TEXT)
          ''');
    });

// 插入數(shù)據(jù)
Future<int> rawInsert(String sql, [List<dynamic> arguments]);

Future<int> insert(String table, Map<String, dynamic> values,
      {String nullColumnHack, ConflictAlgorithm conflictAlgorithm});


// 查詢數(shù)據(jù)
Future<List<Map<String, dynamic>>> rawQuery(String sql,
      [List<dynamic> arguments]);

Future<List<Map<String, dynamic>>> query(String table,
      {bool distinct,
      List<String> columns,
      String where,
      List<dynamic> whereArgs,
      String groupBy,
      String having,
      String orderBy,
      int limit,
      int offset});

// 更新數(shù)據(jù)
Future<int> rawUpdate(String sql, [List<dynamic> arguments]);

Future<int> update(String table, Map<String, dynamic> values,
      {String where,
      List<dynamic> whereArgs,
      ConflictAlgorithm conflictAlgorithm});

// 刪除
Future<int> rawDelete(String sql, [List<dynamic> arguments]);

Future<int> delete(String table, {String where, List<dynamic> whereArgs});

// 關(guān)閉數(shù)據(jù)庫
Future close() async => db.close();

以上就是三種存儲方式的簡單使用。

下面貼一下pubspec.yaml文件中依賴包的代碼:
name: wxq_flutter
description: A new Flutter application.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  #添加新的依賴
  english_words: ^3.1.3

  # 添加sharedPreference依賴
  shared_preferences: ^0.5.0

  # 添加文件依賴
  path_provider: ^0.5.0

  #添加Sqflite依賴
  sqflite: ^1.0.0

   # 引入本地資源圖片
#  assets:
#    - images/pintuan.png

dev_dependencies:
  flutter_test:
    sdk: flutter


# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

參考:
Flutter 數(shù)據(jù)存儲
Flutter 本地存儲
Flutter持久化存儲之數(shù)據(jù)庫存儲

Demo地址:Flutter 數(shù)據(jù)存儲

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容