shared_preferences

shared_preferences 是 Flutter 社区开发的一个本地数据存取插件,它有以下特性:

  • 简单的,异步的,持久化的 key-value 存储系统;
  • 在 Android 上它是基于 SharedPreferences 的;
  • 在 iOS 上它是基于 NSUserDefaults 的;

引入:

  1. dependencies:
  2. shared_preferences: ^0.5.1+

示例:

  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:shared_preferences/shared_preferences.dart';
  4. void main() {
  5. runApp(new MaterialApp(home: new MyApp()));
  6. }
  7. class MyApp extends StatelessWidget {
  8. final String mUserName = "userName";
  9. final _userNameController = new TextEditingController();
  10. @override
  11. Widget build(BuildContext context) {
  12. save() async{
  13. SharedPreferences prefs = await SharedPreferences.getInstance();
  14. prefs.setString(mUserName, _userNameController.value.text.toString());
  15. }
  16. Future<String> get() async {
  17. var userName;
  18. SharedPreferences prefs = await SharedPreferences.getInstance();
  19. userName = prefs.getString(mUserName);
  20. return userName;
  21. }
  22. return new Builder(builder: (BuildContext context) {
  23. return new Scaffold(
  24. appBar: AppBar(
  25. title: Text("SharedPreferences"),
  26. ),
  27. body: Center(
  28. child: new Builder(builder: (BuildContext context){
  29. return
  30. Column(
  31. children: <Widget>[
  32. TextField(
  33. controller: _userNameController,
  34. decoration: InputDecoration(
  35. contentPadding: const EdgeInsets.only(top: 10.0),
  36. icon: Icon(Icons.perm_identity),
  37. labelText: "请输入用户名",
  38. helperText: "注册时填写的名字"
  39. ),
  40. ),
  41. RaisedButton(
  42. color: Colors.blueAccent,
  43. child: Text("存储"),
  44. onPressed: () {
  45. save();
  46. Scaffold.of(context).showSnackBar(
  47. new SnackBar(content: Text("数据存储成功"))
  48. );
  49. }
  50. ),
  51. RaisedButton(
  52. color: Colors.greenAccent,
  53. child: Text("获取"),
  54. onPressed: () {
  55. Future<String> userName = get();
  56. userName.then((String userName) {
  57. Scaffold.of(context).showSnackBar(
  58. SnackBar(content: Text("数据获取成功:$userName"))
  59. );
  60. });
  61. }
  62. ),
  63. ],
  64. );
  65. }),
  66. ),
  67. );
  68. });
  69. }
  70. }

效果:
001.gif

本地存储工具类封装

  1. import 'dart:convert';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. class Storage {
  4. Storage();
  5. static Future get(key) async {
  6. SharedPreferences prefs = await SharedPreferences.getInstance();
  7. return json.decode(prefs.getString(key));
  8. }
  9. static Future set(key, val) async {
  10. SharedPreferences prefs = await SharedPreferences.getInstance();
  11. prefs.setString(key, json.encode(val));
  12. }
  13. }

使用:

  1. FloatingActionButton(
  2. onPressed: () async {
  3. // 存储
  4. Storage.set('name', { 'a': 'hello' });
  5. // 获取
  6. var name = await Storage.get('name');
  7. print(name['a']); // hello
  8. },
  9. child: Icon(Icons.arrow_back),
  10. )

参考资料