Flutter shared_preferences 各种基础用法和特别技巧

这篇博客介绍了Flutter中shared_preferences库的基础用法,包括存储和取出int、String、bool、double、list等数据类型,并展示了如何删除指定数据和清空缓存。此外,作者还分享了如何封装工具类以简化代码,以及如何处理存储model的特别技巧,避免了使用传统方法时的繁琐步骤。最后,提供了项目源码链接和QQ交流群信息。
摘要由CSDN通过智能技术生成

前言

在原生的andriod 和iOS 里面都会有数据缓存的api Android 端用的是 Sharedpreferences 来实现对于轻量级数据的缓存 , IOS端 通常使用NSUserDefaults 来实现轻量级数据的缓存 但是在flutter 有基于Android iOS 做支持的三方插件库 shared_preferences

准备工作

shared_preferences: ^0.5.3+4 (缓存数据)
QQ截图20201108114954.png
在项目里面的pubspec.yaml 添加依赖 然后在项目根目录打开控制台输入 flutter pub get 命令回去下载相对应的依赖

具体实现 :

QQ截图20201108115244.png
QQ20200906-141737.png

好的,这是一个使用 Flutter 操作 shared_preferences 的例程: ```dart import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; @override void initState() { super.initState(); _loadCounter(); } Future<void> _loadCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { _counter = (prefs.getInt('counter') ?? 0); }); } Future<void> _incrementCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { _counter++; prefs.setInt('counter', _counter); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Flutter Shared Preferences Demo"), ), 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), ), ); } } ``` 这个例程演示了如何在 Flutter 中使用 shared_preferences 库来读取和写入应用程序的持久化数据。在这个例子中,我们使用一个整型变量 `_counter` 来记录用户点击按钮的次数。在 `initState` 方法中,我们调用 `_loadCounter` 方法来从 shared_preferences 中读取 `_counter` 的值。在 `_incrementCounter` 方法中,我们调用 `prefs.setInt('counter', _counter)` 来将 `_counter` 的值写入 shared_preferences。每当用户点击按钮时,我们调用 `_incrementCounter` 方法来增加 `_counter` 的值并更新 UI。 注意:为了使用 shared_preferences 库,你需要在 `pubspec.yaml` 文件中添加以下依赖项: ```yaml dependencies: shared_preferences: ^2.0.5 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xq9527--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值