Flutter中如何实现Keychain/Keystore的登录信息保存、填充与删除?
Flutter 实现Keychain/Keystore登录凭证自动填充与管理
核心问题说明
你用flutter_secure_storage保存的凭证默认存在通用安全存储分类中,系统无法识别为登录凭证,因此不会触发自动填充提示,也难以在Keychain对应分类中找到。要实现需求,需要调整存储配置,让系统识别凭证归属,同时配合表单输入框的自动填充属性。
解决方案
1. 配置flutter_secure_storage识别参数
初始化存储时,针对iOS和Android分别配置符合系统自动填充要求的参数:
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; final storage = FlutterSecureStorage( // iOS配置:指定Bundle ID为服务标识,设置为互联网密码类型 iOptions: IOSOptions( service: 'com.yourcompany.yourapp', // 替换为你的应用Bundle ID accessibility: IOSAccessibility.first_unlock, classType: IOSClassType.internetPassword, // 关键:让Keychain识别为登录凭证 server: 'yourapp.com', // 可选:关联的域名,或直接用Bundle ID ), // Android配置:开启自动填充服务支持 aOptions: AndroidOptions( encryptedSharedPreferences: true, autofillService: true, ), );
2. 保存登录凭证
使用上述配置的实例保存邮箱和密码,系统会将凭证归类到登录凭证库:
// 保存邮箱(用户名) await storage.write(key: 'username', value: 'user@example.com'); // 保存密码 await storage.write(key: 'password', value: 'yourpassword');
3. 配置表单输入框触发自动填充
给登录表单的输入框添加自动填充提示,让系统识别输入类型并弹出填充选项:
TextField( decoration: const InputDecoration(labelText: '邮箱'), autofillHints: const [AutofillHints.username, AutofillHints.email], ), TextField( decoration: const InputDecoration(labelText: '密码'), obscureText: true, autofillHints: const [AutofillHints.password], ),
4. 删除Keychain/Keystore中的凭证
直接调用flutter_secure_storage的删除方法即可移除对应凭证:
// 删除单个凭证 await storage.delete(key: 'username'); await storage.delete(key: 'password'); // 清空当前应用所有存储的凭证 await storage.deleteAll();
验证凭证存储位置
- iOS:打开「设置」→「密码」→「网站与应用密码」,就能找到归属你应用的登录凭证(之前找不到是因为默认存在「通用密码」分类,现在切换到互联网密码分类后会被系统识别)
- Android:打开系统「设置」→「密码与安全」→「自动填充服务」→「已保存的密码」,可查看和管理凭证
内容的提问来源于stack exchange,提问作者HPanda
相关产品推荐
相关产品推荐

