赞
踩
shared_preferences
是什么?shared_preferences
?shared_preferences
有那些常用的API?shared_preferences
实现计数器Demo数据存储是开发APP必不可少的一部分,比如页面缓存,从网络上获取数据的本地持久化等,那么在Flutter中如何进行数据存储呢?
Flutter官方推荐我们用sharedpreferences进行数据存储,类似于RN中的
AsyncStorage
。
shared_preferences是Flutter社区开发的一个本地数据存取插件:
SharedPreferences
的;NSUserDefaults
的;首先在pubspec.yaml
文件中添加:
- dependencies:
- shared_preferences: ^0.5.1+
记得运行安装哦:flutter packages get
在需要用到的文件中导入:
import 'package:shared_preferences/shared_preferences.dart';
存储数据
- final prefs = await SharedPreferences.getInstance();
-
- // set value
- prefs.setInt('counter', counter);
读取数据
- final prefs = await SharedPreferences.getInstance();
-
- // Try reading data from the counter key. If it does not exist, return 0.
- final counter = prefs.getInt('counter') ?? 0;}
删除数据
- final prefs = await SharedPreferences.getInstance();
- prefs.remove('counter');
如上图
shared_preferences
支持int, double, bool, string 与 stringList类型的数据存储;
上图
shared_preferences
中所提供的读取相关的API;
- import 'package:flutter/material.dart';
- import 'package:shared_preferences/shared_preferences.dart';
-
- void main() {
- runApp(MaterialApp(
- home: Scaffold(
- appBar: AppBar(
- title: Text('shared_preferences'),
- ),
- body: _CounterWidget(),
- ),
- ));
- }
-
- class _CounterWidget extends StatefulWidget {
- @override
- _CounterState createState() => _CounterState();
- }
-
- class _CounterState extends State<_CounterWidget> {
- String countString = '';
- String localCount = '';
-
- @override
- Widget build(BuildContext context) {
- return Center(
- child: Column(
- children: <Widget>[
- RaisedButton(
- onPressed: _incrementCounter, child: Text('Increment Counter')),
- RaisedButton(onPressed: _getCounter, child: Text('Get Counter')),
- Text(
- countString,
- style: TextStyle(fontSize: 20),
- ),
- Text(
- 'result:' + localCount,
- style: TextStyle(fontSize: 20),
- ),
- ],
- ),
- );
- }
-
- _incrementCounter() async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- setState(() {
- countString = countString + " 1";
- });
- int counter = (prefs.getInt('counter') ?? 0) + 1;
- await prefs.setInt('counter', counter);
- }
-
- _getCounter() async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- setState(() {
- localCount = prefs.getInt('counter').toString();
- });
- }
- }

- import 'package:flutter/material.dart';
- import 'package:shared_preferences/shared_preferences.dart';
-
- class TestSharePreferences extends StatefulWidget {
- @override
- State<StatefulWidget> createState() {
- // TODO: implement createState
- return _TestSharePreferencesState();
- }
- }
-
- class _TestSharePreferencesState extends State<TestSharePreferences> {
- String strInput = '';
- String strLocal = '';
- @override
- Widget build(BuildContext context) {
- // TODO: implement build
- return Column(
- children: [
- Container(
- width: double.infinity,
- ),
- Row(
- // mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Container(
- width: 250,
- child: TextField(
- style: TextStyle(color: Colors.black87),
- decoration: InputDecoration(hintText: "输入要保存的数据"),
- onChanged: (str) {
- strInput = str;
- print('str: $strInput');
- },
- ),
- ),
- Padding(
- padding: EdgeInsets.only(left: 20),
- child: OutlineButton(
- onPressed: () async {
- SharedPreferences sharePreferences =
- await SharedPreferences.getInstance();
- sharePreferences.setString('strLocal', strInput);
- },
- child: Text("保存"),
- ),
- )
- ],
- ),
- Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Container(
- width: 250,
- child: Text("strLocal: $strLocal"),
- ),
- Padding(
- padding: EdgeInsets.only(left: 20),
- child: OutlineButton(
- onPressed: () async {
- SharedPreferences sharePreferences =
- await SharedPreferences.getInstance();
- String message = sharePreferences.getString('strLocal') ?? '';
- setState(() {
- strLocal = message;
- });
- },
- child: Text("读取"),
- ),
- )
- ],
- ),
- ],
- );
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。