在Flutter中,可以通过多种方式进行本地存储和缓存数据,具体方法取决于数据的性质和存储的持久性需求。以下是一些常用的本地存储和缓存方法:
1. SharedPreferences
SharedPreferences用于存储简单的数据类型(如字符串、整数、布尔值等)的键值对,类似于Android中的SharedPreferences或iOS中的UserDefaults。适用于存储简单的配置、设置和用户偏好数据。
使用示例
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('SharedPreferences Example')),
body: PreferenceExample(),
),
);
}
}
class PreferenceExample extends StatefulWidget {
_PreferenceExampleState createState() => _PreferenceExampleState();
}
class _PreferenceExampleState extends State<PreferenceExample> {
String _savedValue = '';
void initState() {
super.initState();
_loadValue();
}
_loadValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_savedValue = prefs.getString('key') ?? 'No Value';
});
}
_saveValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('key', 'Hello, World!');
_loadValue();
}
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Saved Value: $_savedValue'),
ElevatedButton(
onPressed: _saveValue,
child: Text('Save Value'),
),
],
);
}
}
2. File Storage
文件存储适用于存储结构化数据或需要较长时间存储的数据。可以使用Dart的dart:io库来操作文件。常用的存储格式包括JSON、XML等。
使用示例
import 'dart:io';
import 'dart:async';
import

最低0.47元/天 解锁文章
1864

被折叠的 条评论
为什么被折叠?



