SharedPreferences 存儲
緩存少量的鍵值對信息(比如記錄用戶是否閱讀了公告,或是簡單的計數),可以使用 SharedPreferences。
SharedPreferences 會以原生平臺相關的機制,爲簡單的鍵值對數據提供持久化存儲,即在 iOS 上使用 NSUserDefaults,在 Android 使用 SharedPreferences。
SharedPreferences 的使用方式非常簡單方便。不過需要注意的是,以鍵值對的方式只能存儲基本類型的數據,比如 int、double、bool 和 string。
1. pubspec.yaml引入
shared_preferences: 0.5.12+4
2. 代碼
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
//涉及到耗時的文件讀寫,以異步的方式對這些操作進行包裝
//讀取SharedPreferences中key爲counter的值
Future<int> _loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int counter = (prefs.getInt('counter') ?? 0);
return counter;
}
//遞增寫入SharedPreferences中key爲counter的值
Future<void> _incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int counter = (prefs.getInt('counter') ?? 0) + 1;
print("當前值: " + counter.toString());
prefs.setInt('counter', counter); //setter(setInt)方法會同步更新內存中的鍵值對,然後將數據保存至磁盤,因此無需再調用更新方法強制刷新緩存
}
_fresh() {
// _incrementCounter();
_incrementCounter().then((_) => {
_loadCounter().then((value) {
setState(() {
_counter = value;
});
print("before:$value");
})
});
}
// void _incrementCounter() {
// setState(() {
// _counter++;
// });
// }
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
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: _fresh,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
數據庫存儲
如果需要持久化大量格式化後的數據,並且這些數據還會以較高的頻率更新,爲了考慮進一步的擴展性,通常會選用 sqlite 數據庫來應對這樣的場景。
與文件和 SharedPreferences 相比,數據庫在數據讀寫上可以提供更快、更靈活的解決方案。
1. pubspec.yaml引入
sqflite: 1.3.2+1
path_provider: ^1.6.24
2.代碼
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class Student {
String id;
String name;
int score;
//構造方法
Student({
this.id,
this.name,
this.score,
});
//用於將JSON字典轉換成類對象的工廠類方法
factory Student.fromJson(Map<String, dynamic> parsedJson) {
return Student(
id: parsedJson['id'],
name: parsedJson['name'],
score: parsedJson['score'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'score': score,
};
}
}
class _MyHomePageState extends State<MyHomePage> {
var student1 = Student(id: '123', name: '張三', score: 110);
query_database(id) {
Future<Student> user = query_by_id(id);
user.then((t) {
print("單用戶查詢成功");
print('the sroce is : ' + t.score.toString());
student1.score = t.score;
});
}
//插入數據
Future<void> insertStudent(Student std) async {
final Database db = await database;
await db.insert(
'students',
std.toJson(),
//插入衝突策略,新的替換舊的
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<Student> query_by_id(String id) async {
final Database db = await database;
List<Map> maps = await db.query('students',
columns: ['id', 'name', 'score'], where: 'id = ?', whereArgs: [id]);
if (maps.length > 0) {
print("根據id查到了數據");
return Student.fromJson(maps.first);
}
print("根據id沒有查到數據");
return null;
}
//初始化數據庫方法
initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "students_database.db");
return await openDatabase(path, version: 1, onOpen: (db) {},
onCreate: (Database db, int version) async {
await db.execute('''
CREATE TABLE students(id TEXT PRIMARY KEY, name TEXT, score INTEGER)
''');
});
}
Database _database;
Future<Database> get database async {
if (_database != null) {
print(_database);
return _database;
}
_database = await initDB();
print("創建新數據庫");
return _database;
}
void _incrementCounter() async {
student1.score += 1;
await insertStudent(student1);
setState(() {});
}
Future<List<Student>> students() async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('students');
return List.generate(maps.length, (i) => Student.fromJson(maps[i]));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
student1.score.toString(),
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
@override
void dispose() async {
// TODO: implement dispose
super.dispose();
final Database db = await database;
db.close();
}
}