Flutter安全存储插件amplify_secure_storage的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter安全存储插件 amplify_secure_storage 的使用

amplify_secure_storage 是一个用于在Flutter应用中安全存储敏感信息的插件,特别适用于Amplify库。本文将介绍如何使用该插件,并提供一个完整的示例代码。

Pigeon

该插件使用了 pigeon 来实现与主机平台的通信。要重新生成模型,请运行 make pigeons

示例Demo

以下是一个完整的示例代码,展示了如何使用 amplify_secure_storage 插件来读取、写入和删除键值对。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import 'package:amplify_secure_storage/amplify_secure_storage.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(
    const MaterialApp(
      home: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // ignore: invalid_use_of_internal_member
  final storage = AmplifySecureStorage(
    config: AmplifySecureStorageConfig(
      scope: 'test',
      // enabling useDataProtection requires adding the app to an
      // app group, which requires setting a development team
      // ignore: invalid_use_of_visible_for_testing_member
      macOSOptions: MacOSSecureStorageOptions(useDataProtection: false),
    ),
  );
  String _key = '';
  String _value = '';

  void showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  void showException(Exception e) {
    showMessage('An exception occurred: $e');
  }

  void read() async {
    try {
      final value = await storage.read(key: _key);
      showMessage('Value of $_key is: $value');
    } on Exception catch (e) {
      showException(e);
    }
  }

  void write() async {
    try {
      await storage.write(key: _key, value: _value);
      showMessage('Wrote $_key:$_value');
    } on Exception catch (e) {
      showException(e);
    }
  }

  void delete() async {
    try {
      await storage.delete(key: _key);
      showMessage('Removed $_key from storage');
    } on Exception catch (e) {
      showException(e);
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Form(
          child: Column(
            children: [
              TextFormField(
                initialValue: _key,
                decoration: const InputDecoration(
                  label: Text('Key'),
                ),
                onChanged: (value) => setState(() => _key = value),
              ),
              TextFormField(
                initialValue: _value,
                decoration: const InputDecoration(
                  label: Text('Value'),
                ),
                onChanged: (value) => setState(() => _value = value),
              ),
              const SizedBox(height: 8),
              ElevatedButton(
                onPressed: read,
                child: const Text('Read'),
              ),
              ElevatedButton(
                onPressed: write,
                child: const Text('Write'),
              ),
              ElevatedButton(
                onPressed: delete,
                child: const Text('Delete'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter安全存储插件amplify_secure_storage的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter安全存储插件amplify_secure_storage的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用Flutter的amplify_secure_storage插件来进行安全存储的示例代码。这个插件允许你在Flutter应用中安全地存储和检索数据,比如用户凭证、令牌等敏感信息。

首先,确保你已经在你的pubspec.yaml文件中添加了amplify_flutteramplify_secure_storage依赖:

dependencies:
  flutter:
    sdk: flutter
  amplify_flutter: ^0.x.x  # 请检查最新版本号
  amplify_secure_storage: ^0.x.x  # 请检查最新版本号

然后运行flutter pub get来安装这些依赖。

接下来,你需要配置Amplify。在你的项目根目录下创建一个amplifyconfiguration.dart文件,并添加你的配置(这部分配置通常是通过Amplify CLI生成的,但这里为了示例,我们简化它)。

import 'package:amplify_flutter/amplify.dart';

const amplifyconfig = '''
{
    "awscloudformation": {
        "Auth": {
            "Default": {}
        },
        "api": {},
        "storage": {}
    }
}
''';

然后,在你的应用初始化时配置Amplify:

import 'package:flutter/material.dart';
import 'package:amplify_flutter/amplify.dart';
import 'package:amplify_secure_storage/amplify_secure_storage.dart';
import 'amplifyconfiguration.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Amplify.addPlugins([
    AmplifySecureStorage()
  ]);
  try {
    await Amplify.configure(amplifyconfig);
    print('Amplify configured successfully');
    runApp(MyApp());
  } catch (e) {
    print('Failed to configure Amplify: $e');
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SecureStorageExample(),
    );
  }
}

现在,你可以在你的应用中存储和检索数据了。以下是一个简单的例子,展示了如何使用amplify_secure_storage来存储和检索一个用户令牌:

import 'package:flutter/material.dart';
import 'package:amplify_secure_storage/amplify_secure_storage.dart';

class SecureStorageExample extends StatefulWidget {
  @override
  _SecureStorageExampleState createState() => _SecureStorageExampleState();
}

class _SecureStorageExampleState extends State<SecureStorageExample> {
  String _retrievedValue = '';

  void _storeData() async {
    final AmplifySecureStorage storage = AmplifySecureStorage();
    String key = 'USER_TOKEN';
    String value = 'your-secure-token-here';
    
    try {
      await storage.setItem(key: key, value: value);
      print('Item stored successfully');
    } catch (e) {
      print('Failed to store item: $e');
    }
  }

  void _retrieveData() async {
    final AmplifySecureStorage storage = AmplifySecureStorage();
    String key = 'USER_TOKEN';
    
    try {
      String value = await storage.getItem(key: key);
      setState(() {
        _retrievedValue = value ?? 'No data found';
      });
    } catch (e) {
      setState(() {
        _retrievedValue = 'Failed to retrieve data: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Secure Storage Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: _storeData,
              child: Text('Store Data'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _retrieveData,
              child: Text('Retrieve Data'),
            ),
            SizedBox(height: 20),
            Text('Retrieved Value: $_retrievedValue'),
          ],
        ),
      ),
    );
  }
}

这个示例展示了如何使用amplify_secure_storage插件来存储和检索一个键为USER_TOKEN的值。你可以根据需要修改键和值。注意,这个插件在iOS和Android上使用了平台特定的安全存储机制(Keychain和KeyStore),因此可以安全地存储敏感信息。

回到顶部