最近開始著手做Flutter的項目呢堰,研究了一下Flutter的數(shù)據(jù)存儲株依。
Flutter支持Preferences
(Shared Preferences
和 NSUserDefaults
) 读跷、文件和Sqflite
。使用時需要引入官方倉庫的一些相應(yīng)依賴,下面詳細介紹這三種存儲方式的使用方法。
一蝌麸、Preferences:(相當(dāng)于iOS的NSUserDefaults
和Android的SharedPreferences
)
依賴導(dǎo)入步驟:
1)在pubspec.yaml
文件下添加:
# 添加sharedPreference依賴
shared_preferences: ^0.5.0
2)點擊pubspec.yaml
文件右上角的“Packages get
”按鈕或者在當(dāng)前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ù)如下圖:
存儲內(nèi)容展示:
二艾疟、文件存儲:
文件存儲依賴導(dǎo)入方式和Preferences
的依賴導(dǎo)入是一樣的来吩。依賴如下:
# 添加文件依賴
path_provider: ^0.5.0
在 Flutter 里實現(xiàn)文件讀寫,需要使用 path_provider
和 dart
的 io
模塊蔽莱。path_provider
負責(zé)查找iOS
/Android
的目錄文件弟疆,IO
模塊負責(zé)對文件進行讀寫。引用的頭文件如下:
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對象(操作文件記得導(dǎo)入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ù)庫乓诽,并且支持標(biāo)準的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ù)庫展示:
其他方法:創(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持久化存儲之?dāng)?shù)據(jù)庫存儲
Demo地址:Flutter 數(shù)據(jù)存儲