当前位置:   article > 正文

shared_preferences本地存储_shared preferences

shared preferences

基于shared_preferences本地存储操作

  • shared_preferences 是什么?
  • 如何使用shared_preferences
  • shared_preferences有那些常用的API?
  • 基于shared_preferences实现计数器Demo

数据存储是开发APP必不可少的一部分,比如页面缓存,从网络上获取数据的本地持久化等,那么在Flutter中如何进行数据存储呢?

Flutter官方推荐我们用sharedpreferences进行数据存储,类似于RN中的AsyncStorage

什么是shared_preferences?

shared_preferences是Flutter社区开发的一个本地数据存取插件:

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

如何使用shared_preferences?

首先在pubspec.yaml文件中添加:

  1. dependencies:
  2. shared_preferences: ^0.5.1+

记得运行安装哦:flutter packages get

在需要用到的文件中导入:

import 'package:shared_preferences/shared_preferences.dart';

存储数据

  1. final prefs = await SharedPreferences.getInstance();
  2. // set value
  3. prefs.setInt('counter', counter);

读取数据

  1. final prefs = await SharedPreferences.getInstance();
  2. // Try reading data from the counter key. If it does not exist, return 0.
  3. final counter = prefs.getInt('counter') ?? 0;}

删除数据

  1. final prefs = await SharedPreferences.getInstance();
  2. prefs.remove('counter');

shared_preferences有那些常用的API?

存储相关

shared_preferences

如上图shared_preferences支持int, double, bool, string 与 stringList类型的数据存储;

读取相关

shared_preferences

上图shared_preferences中所提供的读取相关的API;

基于shared_preferences实现计数器Demo

shared_preferences

  1. import 'package:flutter/material.dart';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. void main() {
  4. runApp(MaterialApp(
  5. home: Scaffold(
  6. appBar: AppBar(
  7. title: Text('shared_preferences'),
  8. ),
  9. body: _CounterWidget(),
  10. ),
  11. ));
  12. }
  13. class _CounterWidget extends StatefulWidget {
  14. @override
  15. _CounterState createState() => _CounterState();
  16. }
  17. class _CounterState extends State<_CounterWidget> {
  18. String countString = '';
  19. String localCount = '';
  20. @override
  21. Widget build(BuildContext context) {
  22. return Center(
  23. child: Column(
  24. children: <Widget>[
  25. RaisedButton(
  26. onPressed: _incrementCounter, child: Text('Increment Counter')),
  27. RaisedButton(onPressed: _getCounter, child: Text('Get Counter')),
  28. Text(
  29. countString,
  30. style: TextStyle(fontSize: 20),
  31. ),
  32. Text(
  33. 'result:' + localCount,
  34. style: TextStyle(fontSize: 20),
  35. ),
  36. ],
  37. ),
  38. );
  39. }
  40. _incrementCounter() async {
  41. SharedPreferences prefs = await SharedPreferences.getInstance();
  42. setState(() {
  43. countString = countString + " 1";
  44. });
  45. int counter = (prefs.getInt('counter') ?? 0) + 1;
  46. await prefs.setInt('counter', counter);
  47. }
  48. _getCounter() async {
  49. SharedPreferences prefs = await SharedPreferences.getInstance();
  50. setState(() {
  51. localCount = prefs.getInt('counter').toString();
  52. });
  53. }
  54. }

参考

 

  1. import 'package:flutter/material.dart';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. class TestSharePreferences extends StatefulWidget {
  4. @override
  5. State<StatefulWidget> createState() {
  6. // TODO: implement createState
  7. return _TestSharePreferencesState();
  8. }
  9. }
  10. class _TestSharePreferencesState extends State<TestSharePreferences> {
  11. String strInput = '';
  12. String strLocal = '';
  13. @override
  14. Widget build(BuildContext context) {
  15. // TODO: implement build
  16. return Column(
  17. children: [
  18. Container(
  19. width: double.infinity,
  20. ),
  21. Row(
  22. // mainAxisAlignment: MainAxisAlignment.center,
  23. children: [
  24. Container(
  25. width: 250,
  26. child: TextField(
  27. style: TextStyle(color: Colors.black87),
  28. decoration: InputDecoration(hintText: "输入要保存的数据"),
  29. onChanged: (str) {
  30. strInput = str;
  31. print('str: $strInput');
  32. },
  33. ),
  34. ),
  35. Padding(
  36. padding: EdgeInsets.only(left: 20),
  37. child: OutlineButton(
  38. onPressed: () async {
  39. SharedPreferences sharePreferences =
  40. await SharedPreferences.getInstance();
  41. sharePreferences.setString('strLocal', strInput);
  42. },
  43. child: Text("保存"),
  44. ),
  45. )
  46. ],
  47. ),
  48. Row(
  49. mainAxisAlignment: MainAxisAlignment.center,
  50. children: [
  51. Container(
  52. width: 250,
  53. child: Text("strLocal: $strLocal"),
  54. ),
  55. Padding(
  56. padding: EdgeInsets.only(left: 20),
  57. child: OutlineButton(
  58. onPressed: () async {
  59. SharedPreferences sharePreferences =
  60. await SharedPreferences.getInstance();
  61. String message = sharePreferences.getString('strLocal') ?? '';
  62. setState(() {
  63. strLocal = message;
  64. });
  65. },
  66. child: Text("读取"),
  67. ),
  68. )
  69. ],
  70. ),
  71. ],
  72. );
  73. }
  74. }

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号