本地存储
小于 1 分钟flutter
shared_preferences

案例
注意插件 shared_preference 要求 NDK 版本至少为 27.0.12077973,所以需要到文件 项目根目录/android/app/build.gradle.kts 中修改为 ndkVersion = "27.0.12077973" 再运行项目
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Storage extends StatefulWidget {
const Storage({super.key});
State<Storage> createState() => _StorageState();
}
class _StorageState extends State<Storage> {
String countString = '';
String localCount = '';
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('storage实现计数器')),
body: Column(
children: [
ElevatedButton(onPressed: _incrementCounter, child: const Text('Increment Counter')),
ElevatedButton(onPressed: _getCounter, child: const Text('Get Counter')),
Text(countString,style: const TextStyle(fontSize: 20),),
Text('result:$localCount', style: const TextStyle(fontSize: 20))
],
),
);
}
void _incrementCounter() async {
setState(() {
countString = '$countString 1';
});
SharedPreferences prefs = await SharedPreferences.getInstance();
int newCounter = (prefs.getInt('counter') ?? 0) + 1;
await prefs.setInt('counter', newCounter);
}
void _getCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
localCount = (prefs.getInt('counter') ?? 0).toString();
});
}
}
缓存插件 flutter_hi_cache
在依赖中添加 flutter_hi_cache: ^0.0.1
