Flutter安全存储插件flutter_secure_storage_windows_per的使用
Flutter安全存储插件flutter_secure_storage_windows
的使用
简介
flutter_secure_storage_windows
是 flutter_secure_storage
插件的 Windows 平台实现。它允许开发者在 Windows 应用程序中安全地存储和检索敏感数据。
使用方法
此包是官方推荐的 endorsed federated 插件之一,因此您可以直接使用 flutter_secure_storage
包。当您这样做时,此包会自动包含在您的应用程序中。
完整示例代码
以下是一个完整的示例,展示如何使用 flutter_secure_storage_windows
插件进行安全存储。
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_secure_storage_platform_interface/flutter_secure_storage_platform_interface.dart';
import 'package:flutter_secure_storage_windows/flutter_secure_storage_windows.dart';
// 测试应用。
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
State<MyApp> createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
final TextEditingController keyFieldController = TextEditingController();
final TextEditingController valueFieldController = TextEditingController();
final TextEditingController resultSummaryFieldController = TextEditingController();
final TextEditingController resultDetailFieldController = TextEditingController();
final GlobalKey<LabeledCheckboxState> useMethodChannelOnlyKey = GlobalKey();
final GlobalKey<LabeledCheckboxState> useBackwardCompatibilityKey = GlobalKey();
Future<TestResult>? _future;
FlutterSecureStoragePlatform _flutterSecureStorageWindowsPlugin =
FlutterSecureStorageWindows();
final Map<String, String> _options = {'useBackwardCompatibility': 'false'};
[@override](/user/override)
void initState() {
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: Padding(
padding: const EdgeInsets.all(8),
child: Column(children: [
TextField(
controller: keyFieldController,
decoration: const InputDecoration(label: Text('键')),
),
TextField(
controller: valueFieldController,
decoration: const InputDecoration(label: Text('值')),
),
LabeledCheckbox(
key: useMethodChannelOnlyKey,
initialValue: false,
label: '仅使用MethodChannel',
onChanged: (useMethodChannelOnly) {
setState(() {
_flutterSecureStorageWindowsPlugin = useMethodChannelOnly
? MethodChannelFlutterSecureStorage()
: FlutterSecureStorageWindows();
});
},
),
LabeledCheckbox(
key: useBackwardCompatibilityKey,
initialValue: false,
label: '使用向后兼容性',
onChanged: (useBackwardCompatibility) {
setState(() {
_options['useBackwardCompatibility'] =
useBackwardCompatibility.toString();
});
},
),
Row(
children: [
Padding(
padding: const EdgeInsets.all(4),
child: ElevatedButton(
onPressed: doRead,
child: const Text('读取'),
),
),
Padding(
padding: const EdgeInsets.all(4),
child: ElevatedButton(
onPressed: doReadAll,
child: const Text('读取所有'),
),
),
Padding(
padding: const EdgeInsets.all(4),
child: ElevatedButton(
onPressed: doContainsKey,
child: const Text('检查键是否存在'),
),
),
],
),
Row(
children: [
Padding(
padding: const EdgeInsets.all(4),
child: ElevatedButton(
onPressed: doWrite,
child: const Text('写入'),
),
),
Padding(
padding: const EdgeInsets.all(4),
child: ElevatedButton(
onPressed: doDelete,
child: const Text('删除'),
),
),
Padding(
padding: const EdgeInsets.all(4),
child: ElevatedButton(
onPressed: doDeleteAll,
child: const Text('删除所有'),
),
),
],
),
Row(
children: [
Padding(
padding: const EdgeInsets.all(4),
child: ElevatedButton(
onPressed: doLegacyWrite,
child: const Text('遗留写入'),
),
),
Padding(
padding: const EdgeInsets.all(4),
child: ElevatedButton(
onPressed: doLegacyReadAll,
child: const Text('遗留读取所有'),
),
),
],
),
if (_future != null)
FutureBuilder<TestResult>(
builder: (context, snapshot) {
if (!snapshot.hasData && !snapshot.hasError) {
return const CircularProgressIndicator();
}
resultSummaryFieldController.text =
(snapshot.data?.success ?? false) ? '成功' : '失败';
return TextField(
controller: resultSummaryFieldController,
decoration: const InputDecoration(label: Text('结果')),
);
},
future: _future,
),
if (_future != null)
FutureBuilder<TestResult>(
builder: (context, snapshot) {
if (!snapshot.hasData && !snapshot.hasError) {
return const CircularProgressIndicator();
}
resultDetailFieldController.text =
snapshot.error?.toString() ??
snapshot.data!.detail ??
'<null>';
return Column(
children: [
TextField(
controller: resultSummaryFieldController,
decoration:
const InputDecoration(label: Text('结果')),
),
TextField(
controller: resultDetailFieldController,
decoration:
const InputDecoration(label: Text('详细信息')),
),
],
);
},
future: _future,
),
// const Expanded(child: SizedBox()),
]),
),
),
);
}
Future<TestResult> doTestCore(FutureOr<TestResult> Function() test) async {
late final TestResult result;
try {
result = await test();
} catch (e, s) {
debugPrint(e.toString());
debugPrintStack(stackTrace: s);
result = TestResult(success: false, detail: e.toString());
}
return result;
}
void doTest(FutureOr<TestResult> Function() test) {
setState(() {
_future = doTestCore(test);
});
}
void doRead() => doTest(() async {
final key = keyFieldController.text;
return TestResult(
success: true,
detail: await _flutterSecureStorageWindowsPlugin.read(
key: key,
options: _options,
),
);
});
void doReadAll() => doTest(() async {
return TestResult(
success: true,
detail: (await _flutterSecureStorageWindowsPlugin.readAll(
options: _options,
))
.toString(),
);
});
void doContainsKey() => doTest(() async {
final key = keyFieldController.text;
return TestResult(
success: true,
detail: (await _flutterSecureStorageWindowsPlugin.containsKey(
key: key,
options: _options,
))
.toString(),
);
});
void doWrite() => doTest(() async {
final key = keyFieldController.text;
final value = valueFieldController.text.isNotEmpty
? valueFieldController.text
: DateTime.now().toIso8601String();
await _flutterSecureStorageWindowsPlugin.write(
key: key,
value: value,
options: _options,
);
return TestResult(success: true, detail: value);
});
void doDelete() => doTest(() async {
final key = keyFieldController.text;
await _flutterSecureStorageWindowsPlugin.delete(
key: key,
options: _options,
);
return TestResult(
success: true,
detail: null,
);
});
void doDeleteAll() => doTest(() async {
await _flutterSecureStorageWindowsPlugin.deleteAll(
options: _options,
);
return TestResult(
success: true,
detail: null,
);
});
void doLegacyWrite() => doTest(() async {
final key = keyFieldController.text;
final value = valueFieldController.text.isNotEmpty
? valueFieldController.text
: DateTime.now().toIso8601String();
// 调用 MethodChannelFlutterSecureStorage 直接
final legacyStorage = MethodChannelFlutterSecureStorage();
await legacyStorage.write(
key: key,
value: value,
options: _options,
);
return TestResult(success: true, detail: value);
});
void doLegacyReadAll() => doTest(() async {
// 调用 MethodChannelFlutterSecureStorage 直接
final legacyStorage = MethodChannelFlutterSecureStorage();
return TestResult(
success: true,
detail: (await legacyStorage.readAll(
options: _options,
))
.toString());
});
}
class TestResult {
final bool success;
final String? detail;
TestResult({
required this.success,
required this.detail,
});
}
class LabeledCheckbox extends StatefulWidget {
final String label;
final EdgeInsetsGeometry padding;
final bool initialValue;
final ValueChanged<bool>? onChanged;
const LabeledCheckbox({
Key? key,
required this.label,
this.padding = const EdgeInsets.all(4),
this.initialValue = false,
this.onChanged,
}) : super(key: key);
[@override](/user/override)
State<StatefulWidget> createState() => LabeledCheckboxState._();
}
class LabeledCheckboxState extends State<LabeledCheckbox> {
late bool _value;
bool get value => _value;
set value(bool v) {
setState(() {
_value = v;
});
widget.onChanged?.call(v);
}
LabeledCheckboxState._();
[@override](/user/override)
void initState() {
super.initState();
_value = widget.initialValue;
}
[@override](/user/override)
Widget build(BuildContext context) => InkWell(
onTap: () {
value = !value;
},
child: Padding(
padding: widget.padding,
child: Row(children: [
Expanded(child: Text(widget.label)),
Checkbox(
value: value,
onChanged: (newValue) {
if (newValue != null) {
value = newValue;
}
})
]),
),
);
}
更多关于Flutter安全存储插件flutter_secure_storage_windows_per的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter安全存储插件flutter_secure_storage_windows_per的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_secure_storage_windows_per
是一个用于在 Windows 平台上安全存储数据的 Flutter 插件。它是 flutter_secure_storage
插件的一个扩展,专门为 Windows 平台提供支持。使用这个插件,你可以在 Windows 应用程序中安全地存储敏感数据,如 API 密钥、令牌等。
安装插件
首先,你需要在 pubspec.yaml
文件中添加 flutter_secure_storage_windows_per
插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_secure_storage: ^5.0.0
flutter_secure_storage_windows_per: ^1.0.0
然后运行 flutter pub get
来安装依赖。
使用插件
-
导入插件
在你的 Dart 文件中导入
flutter_secure_storage
和flutter_secure_storage_windows_per
:import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage_windows_per/flutter_secure_storage_windows_per.dart';
-
初始化插件
在使用插件之前,你需要初始化它。通常,你可以在
main
函数中进行初始化:void main() { // 初始化插件 FlutterSecureStorageWindowsPer.registerWith(); runApp(MyApp()); }
-
使用
FlutterSecureStorage
现在你可以使用
FlutterSecureStorage
来存储和读取数据。以下是一些基本的使用示例:class MyApp extends StatelessWidget { final FlutterSecureStorage _storage = FlutterSecureStorage(); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Secure Storage Example'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () async { // 存储数据 await _storage.write(key: 'my_key', value: 'my_value'); print('Data stored'); }, child: Text('Store Data'), ), ElevatedButton( onPressed: () async { // 读取数据 String? value = await _storage.read(key: 'my_key'); print('Data read: $value'); }, child: Text('Read Data'), ), ElevatedButton( onPressed: () async { // 删除数据 await _storage.delete(key: 'my_key'); print('Data deleted'); }, child: Text('Delete Data'), ), ], ), ), ), ); } }