Flutter本地存儲javascript
和Android、Ios相似,Flutter也支持Preferences(Shared Preferences and NSUserDefaults) 、文件、和Sqlite3。java
只不過要想使用這個功能須要引入官方倉庫的相應插件,那麼咱們就分別來看下這三種存儲方式的使用方法。git
Flutter中自己並不支持Preferences存儲,須要藉助於第三發的組件來實現。 github
插件搜索地址: https://pub.flutter-io.cn/packages/
app
在右側選擇github便可進入github下載less
下載後配置異步
此處配置省略....async
(shared_preferences)使用:ide
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { runApp(MaterialApp(home: MyApp())); } class MyApp extends StatelessWidget { final String mUserName = "userName"; final _userNameController = new TextEditingController(); @override Widget build(BuildContext context) { save() async{ SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString(mUserName, _userNameController.value.text.toString()); } Future<String> get() async { var userName; SharedPreferences prefs = await SharedPreferences.getInstance(); userName = prefs.getString(mUserName); return userName; } return new Builder(builder: (BuildContext context) { return new Scaffold( appBar: AppBar( title: Text("SharedPreferences"), ), body: Center( child: new Builder(builder: (BuildContext context){ return Column( children: <Widget>[ TextField( controller: _userNameController, decoration: InputDecoration( contentPadding: const EdgeInsets.only(top: 10.0), icon: Icon(Icons.perm_identity), labelText: "請輸入用戶名", helperText: "註冊時填寫的名字"), ), RaisedButton( color: Colors.blueAccent, child: Text("存儲"), onPressed: () { save(); Scaffold.of(context).showSnackBar( new SnackBar(content: Text("數據存儲成功"))); }), RaisedButton( color: Colors.greenAccent, child: Text("獲取"), onPressed: () { Future<String> userName = get(); userName.then((String userName) { Scaffold.of(context).showSnackBar( SnackBar(content: Text("數據獲取成功:$userName"))); }); }), ], ); }), ), ); }); } }
加上async和await關鍵字,由於SharedPreferences的存貯也是一個輕量級的耗時操做,因此須要在異步中進行的。ui
使用SharedPreferences.getInstance()方法來實例化SharedPreferences對象,使用它的setString方法來存儲用戶輸入的字符串。
setString(key, value) 其中key就是你存貯的名稱,value就是你存儲的值
Future save() async{ SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString(mUserName, _userNameController.value.text.toString()); }
..傳參: Future set(String key,String value) async{ //根據傳入參數進行查詢 ... prefs.setString(key,value); }
SharedPreferences存儲其餘對象方法:
prefs.setBool(key, value) prefs.setDouble(key, value) prefs.setInt(key, value) prefs.setStringList(key, value)
get方法:
Future<String> get() async { var userName; SharedPreferences prefs = await SharedPreferences.getInstance(); userName = await prefs.getString(mUserName); return userName; }
......後續更新