Flutter本地存储之基本的键值对存储详解
作者:岛上码农 时间:2023-08-18 03:52:35
前言
在原生的 Android 或 iOS 中,都提供了基本的键值对存储方式,Android 是 SharedPreferences
,iOS 是 NSUserDefaults
。在 Flutter 中,提供了 shared_preferences
这个插件来实现本地键值对数据存储。实际上,shared_preferences
在 Android 就是使用 SharedPreferences 实现,在 iOS 上则是使用 NSUserDefaults
实现。
基本使用
在 pubspec.yaml 文件中添加以下代码:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.18
我们将基础的计数应用修改为支持从上一次结果(即存储在本地的数值)开始增加。代码如下:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _counter = 0;
late SharedPreferences _prefs;
@override
void initState() {
super.initState();
_loadCounter();
}
void _loadCounter() async {
_prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (_prefs.getInt('counter') ?? 0);
});
}
void _incrementCounter() async {
setState(() {
_counter++;
});
await _prefs.setInt('counter', _counter);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Shared Preferences 示例'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
),
);
}
}
上面的代码是一个基础的计数器应用,我们定义了一个_counter
变量来保存计数器的值,并且使用 SharedPreferences
实例来存储和检索_counter
变量的值。 在initState
方法中,我们使用_loadCounter
方法来加载_counter
变量的值。在_loadCounter
方法中,我们首先使用SharedPreferences.getInstance()
方法来获取 SharedPreferences
实例,然后使用 getInt()
方法来检索 _counter
变量的值。如果检索到的值为 null
,则将 _counter
变量的值设置为 0。 在 _incrementCounter
方法中,我们使用了setInt
方法将 _counter
变量的值保存到 SharedPreferences
实例中来实现本地存储。 运行效果如下:
存储其他类型数据
shared_preferences
支持存储的数据类型有整型、浮点型(double)、字符串、布尔型和字符串数组。如果想存储对象,也可以通过 json
序列化和反序列化的方式实现。我们来看一个更复杂点的例子。
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// 初始化需要存储的值
int _counter = 0;
String _username = '';
bool _isDarkModeEnabled = false;
final _textController = TextEditingController(text: '');
// SharedPreferences 实例
late SharedPreferences _prefs;
// 加载 SharedPreferences 中存储的值
Future<void> _loadData() async {
_prefs = await SharedPreferences.getInstance();
setState(() {
_counter = _prefs.getInt('counter') ?? 0;
_username = _prefs.getString('username') ?? '';
_textController.text = _username;
_isDarkModeEnabled = _prefs.getBool('isDarkModeEnabled') ?? false;
});
}
void _incrementCounter() async {
setState(() {
_counter++;
});
await _prefs.setInt('counter', _counter);
}
// 保存用户名
void _saveUsername(String username) async {
setState(() {
_username = username;
});
await _prefs.setString('username', _username);
}
// 切换暗黑模式
void _toggleDarkMode(bool isDarkModeEnabled) async {
setState(() {
_isDarkModeEnabled = isDarkModeEnabled;
});
await _prefs.setBool('isDarkModeEnabled', _isDarkModeEnabled);
}
@override
void initState() {
super.initState();
_loadData();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter SharedPreferences 示例',
theme: _isDarkModeEnabled ? ThemeData.dark() : ThemeData.light(),
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter SharedPreferences 示例'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'计数器的值:$_counter',
),
const SizedBox(height: 20),
TextFormField(
decoration: const InputDecoration(
labelText: '请输入您的名字',
),
controller: _textController,
onChanged: (value) {
_saveUsername(value);
},
),
const SizedBox(height: 20),
SwitchListTile(
title: const Text('启用暗黑模式'),
value: _isDarkModeEnabled,
onChanged: (value) {
_toggleDarkMode(value);
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: '递增计数器的值',
child: const Icon(Icons.add),
),
),
);
}
}
上述代码增加了两个类型的存储,分别是字符串和布尔型,存储方式其实是类似的,布尔型使用 getBool
获取、setBool
存储;字符串则是使用 getString
和 setString
。我们通过布尔型变量控制是否启用暗黑模式,使用字符串类存储用户名。下面是运行的结果。
来源:https://juejin.cn/post/7212548831723470907
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
springBoot的事件机制GenericApplicationListener用法解析
Java 实战项目锤炼之网上图书馆管理系统的实现流程
![](https://img.aspxhome.com/file/2023/7/121957_0s.png)
Java Socket编程(五) 简单的WEB服务器
Java时间工具类Date的常用处理方法
Java实现双保险线程的示例代码
java中Statement 与 PreparedStatement接口之间的关系和区别
![](https://img.aspxhome.com/file/2023/9/60029_0s.png)
Java实现单例模式的五种方法介绍
Java中判断对象是否为空的方法的详解
Android 中Volley二次封装并实现网络请求缓存
C#单例类的实现方法
C#/VB.NET 实现彩色PDF转为灰度PDF
![](https://img.aspxhome.com/file/2023/9/92889_0s.jpg)
Java ByteBuffer网络编程用法实例解析
![](https://img.aspxhome.com/file/2023/5/107555_0s.jpg)
ShardingSphere jdbc集成多数据源的实现步骤
![](https://img.aspxhome.com/file/2023/6/59766_0s.png)
解决RestTemplate反序列化嵌套对象的问题
![](https://img.aspxhome.com/file/2023/7/83417_0s.png)
Java 中解决Unsupported major.minor version 51.0的问题
![](https://img.aspxhome.com/file/2023/6/62516_0s.jpg)
C#使用XML序列化操作菜单的方法
Android实现Activity水平和垂直滚动条的方法
浅析C#中数组,ArrayList与List对象的区别
Android数据存储方式操作模式解析
flutter Container容器实现圆角边框
![](https://img.aspxhome.com/file/2023/1/110731_0s.gif)