shared_preferences
shared_preferences 是 Flutter 社区开发的一个本地数据存取插件,它有以下特性:
- 简单的,异步的,持久化的 key-value 存储系统;
- 在 Android 上它是基于 SharedPreferences 的;
- 在 iOS 上它是基于 NSUserDefaults 的;
引入:
dependencies:shared_preferences: ^0.5.1+
示例:
import 'dart:async';import 'package:flutter/material.dart';import 'package:shared_preferences/shared_preferences.dart';void main() {runApp(new MaterialApp(home: new MyApp()));}class MyApp extends StatelessWidget {final String mUserName = "userName";final _userNameController = new TextEditingController();@overrideWidget 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){returnColumn(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")));});}),],);}),),);});}}
效果:
本地存储工具类封装
import 'dart:convert';import 'package:shared_preferences/shared_preferences.dart';class Storage {Storage();static Future get(key) async {SharedPreferences prefs = await SharedPreferences.getInstance();return json.decode(prefs.getString(key));}static Future set(key, val) async {SharedPreferences prefs = await SharedPreferences.getInstance();prefs.setString(key, json.encode(val));}}
使用:
FloatingActionButton(onPressed: () async {// 存储Storage.set('name', { 'a': 'hello' });// 获取var name = await Storage.get('name');print(name['a']); // hello},child: Icon(Icons.arrow_back),)
