Flutter安全存储插件potatoes_secured_preferences的使用
Flutter安全存储插件potatoes_secured_preferences的使用
Potatoes Secured Preferences
是一个具备安全存储功能的偏好设置服务。它基于 Potatoes
构建,并使用 flutter_secure_storage
来提供加密能力。
开始使用
该插件提供了对 Potatoes
的 PreferencesService
的扩展,通过 flutter_secure_storage
提供加密功能。
使用方法
你需要扩展 SecuredPreferencesService
类来定义持久化逻辑。
class AppSecuredPreferences extends SecuredPreferencesService {
static const String _authTokenKey = 'auth_token';
static const String _userIdKey = 'user_id';
AppSecuredPreferences(super.preferences, super.secureStorage);
// 不需要加密,我们使用常规的SharedPreferences
Future<void> setUserId(String value) {
return preferences.setString(_userIdKey, value);
}
String? get userId => preferences.getString(_userIdKey);
// 加密敏感值
Future<void> setAuthToken(String value) {
return secureStorage.write(key: _authTokenKey, value: value);
}
[@override](/user/override)
FutureOr<Map<String, String>> getAuthHeaders() async {
// 从Secure Storage获取认证令牌
final token = await secureStorage.read(key: _authTokenKey);
// 返回auth map以注入到API查询中
return {
'Authorization': 'Bearer $token'
};
}
}
你可以这样使用它:
// 创建新实例
securedPreferencesService = AppSecuredPreferences(
sharedPreferences,
flutterSecureStorage
);
securedPreferencesService.setUserId("user id here");
securedPreferencesService.userId; // 获取用户ID值
securedPreferencesService.setAuthToken("token value here");
// 清除SharedPreferences和Secure Storage
securedPreferencesService.clear();
完整示例Demo
以下是完整的示例代码:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:potatoes_secured_preferences/potatoes_secured_preferences.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final AppSecuredPreferences securedPreferencesService;
[@override](/user/override)
void initState() {
super.initState();
// 初始化Secured preferences与SharedPreferences和FlutterSecureStorage
SharedPreferences.getInstance().then((preferences) {
securedPreferencesService = AppSecuredPreferences(
preferences,
const FlutterSecureStorage()
);
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: const Center(
child: Text('Hello from Potatoes'),
),
),
);
}
}
class AppSecuredPreferences extends SecuredPreferencesService {
static const String _authTokenKey = 'auth_token';
static const String _userIdKey = 'user_id';
AppSecuredPreferences(super.preferences, super.secureStorage);
// 不需要加密,我们使用常规的SharedPreferences
Future<void> setUserId(String value) {
return preferences.setString(_userIdKey, value);
}
String? get userId => preferences.getString(_userIdKey);
// 加密敏感值
Future<void> setAuthToken(String value) {
return secureStorage.write(key: _authTokenKey, value: value);
}
[@override](/user/override)
FutureOr<Map<String, String>> getAuthHeaders() async {
// 从Secure Storage获取认证令牌
final token = await secureStorage.read(key: _authTokenKey);
// 返回auth map以注入到API查询中
return {
'Authorization': 'Bearer $token'
};
}
}
更多关于Flutter安全存储插件potatoes_secured_preferences的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter安全存储插件potatoes_secured_preferences的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter应用中使用potatoes_secured_preferences
插件进行安全存储的示例代码。potatoes_secured_preferences
是一个用于在Flutter应用中安全存储数据的插件,它基于shared_preferences
,但增加了额外的加密层来保护数据。
首先,确保你已经在pubspec.yaml
文件中添加了potatoes_secured_preferences
依赖:
dependencies:
flutter:
sdk: flutter
potatoes_secured_preferences: ^x.y.z # 替换为最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,是一个使用potatoes_secured_preferences
进行安全存储和读取数据的示例:
import 'package:flutter/material.dart';
import 'package:potatoes_secured_preferences/potatoes_secured_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Secure Storage Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _keyController = TextEditingController();
final _valueController = TextEditingController();
@override
void dispose() {
_keyController.dispose();
_valueController.dispose();
super.dispose();
}
Future<void> _saveData() async {
final potatoes = PotatoesSecuredPreferences();
String key = _keyController.text;
String value = _valueController.text;
try {
await potatoes.setString(key, value);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Data saved successfully!')),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to save data: $e')),
);
}
}
Future<void> _readData() async {
final potatoes = PotatoesSecuredPreferences();
String key = _keyController.text;
try {
String? value = await potatoes.getString(key);
if (value != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Value for '$key': $value")),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("No value found for '$key'")),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to read data: $e')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Secure Storage Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _keyController,
decoration: InputDecoration(labelText: 'Key'),
),
SizedBox(height: 16),
TextField(
controller: _valueController,
decoration: InputDecoration(labelText: 'Value'),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: _saveData,
child: Text('Save Data'),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: _readData,
child: Text('Read Data'),
),
],
),
),
);
}
}
这个示例展示了如何使用potatoes_secured_preferences
插件来存储和读取键值对数据。用户可以在UI中输入键和值,然后点击“Save Data”按钮来存储数据,或者点击“Read Data”按钮来读取数据。
注意:在实际应用中,你可能需要处理更多的错误情况,并且可能需要在应用启动时初始化PotatoesSecuredPreferences
实例,这取决于你的具体需求。此外,确保你已经理解了加密密钥的管理,因为potatoes_secured_preferences
依赖于一个加密密钥来保护存储的数据。