字
字节笔记本
2026年2月22日
flutter-swift-documentscan:Flutter + Swift VisionKit 文档扫描示例
本文介绍 flutter-swift-documentscan,一个使用 Swift Native VisionKit 实现文档扫描功能的 Flutter 应用示例项目。该项目展示了如何通过 Flutter Method Channel 与 iOS 原生代码进行通信,实现文档扫描、PDF 打印和安全密钥链存储等功能。
项目简介
flutter-swift-documentscan 是一个开源的 Flutter 示例项目,由 Baris Tikir 开发维护。该项目演示了如何在 Flutter 应用中调用 iOS 原生功能,包括 VisionKit 文档扫描、AirPrint 打印和安全密钥链访问。截至目前,该项目在 GitHub 上已获得 4 stars,采用 MIT 许可证开源。
核心特性
- iOS VisionKit 文档扫描:通过 Method Channel 调用 Swift 原生文档扫描功能
- AirPrint PDF 打印:支持从网络下载 PDF 并调用原生打印功能
- 安全密钥链存储:演示 iOS Secure Keychain 的读写删除操作
- Method Channel 通信:完整的 Flutter 与 iOS 原生代码双向通信示例
- 多平台架构支持:支持 iOS 原生功能集成
技术栈
- Dart (55.7%) - Flutter 应用主体
- Swift (40.7%) - iOS 原生 Method Channel 实现
- Ruby (3.2%) - CocoaPods 配置
项目结构
text
lib/
├── main.dart # 主应用入口,包含 Method Channel 调用示例
ios/
├── Runner/
│ └── AppDelegate.swift # iOS 原生 Method Channel 处理器核心代码解析
1. Method Channel 定义
dart
// 定义 Method Channel(与 iOS 端保持一致)
final platform = const MethodChannel("com.flutter.baristikir/baristikir");2. 文档扫描功能
dart
// 调用 iOS VisionKit 文档扫描
Future<List<String>> _scanDocument() async {
List<dynamic> images = await platform.invokeMethod("SDScanDocument");
return images.map((e) => e.toString()).toList();
}3. PDF 打印功能
dart
// 下载 PDF 文件
Future<File> _downloadFile(String url, String filename) async {
http.Client _client = new http.Client();
var req = await _client.get(Uri.parse(url));
var bytes = req.bodyBytes;
String dir = (await getApplicationDocumentsDirectory()).path;
File file = new File('$dir/$filename');
await file.writeAsBytes(bytes);
return file;
}
// 调用 iOS AirPrint 打印
Future<void> _printDocument(String b64Bytes, String filePath) async {
var e = await platform.invokeMethod("SDPrintPDF", {"bytes": b64Bytes});
}4. 安全密钥链操作
dart
// 使用 flutter_secure_storage 包操作 iOS Keychain
final _storage = SecureKeychainService();
void _addToKeychain(String key, String value) async {
await _storage.write(key: key, value: value, iosOptions: _getIOSOptions());
}
void _readFromKeychain(String key) async {
await _storage.read(key: key, iosOptions: _getIOSOptions());
}
void _removeFromKeychain(String key) async {
await _storage.delete(key: key, iosOptions: _getIOSOptions());
}快速开始
前置要求
- Flutter SDK >= 2.0
- iOS 13.0+(VisionKit 要求)
- Xcode 12+
- macOS 开发环境
安装步骤
bash
# 克隆项目
git clone https://github.com/baristikir/flutter-swift-documentscan.git
cd flutter-swift-documentscan
# 安装依赖
flutter pub get
# 进入 iOS 目录安装 Pod
cd ios && pod install && cd ..
# 运行应用
flutter runiOS 配置
确保 ios/Podfile 中平台版本不低于 13.0:
ruby
platform :ios, '13.0'功能演示
应用界面包含以下功能按钮:
- Scan Documents - 启动 iOS VisionKit 文档扫描器
- Print Document - 下载测试 PDF 并调用 AirPrint 打印
- Set Value to Keychain - 存储键值对到安全密钥链
- Get Value from Keychain - 从密钥链读取值
- Remove Value from Keychain - 从密钥链删除值
注意事项
- 文档扫描功能仅在 iOS 13.0+ 设备上可用
- 打印功能需要设备连接支持 AirPrint 的打印机
- 密钥链操作需要正确的 iOS 配置和权限
- 该项目为示例性质,生产环境使用前需进行适当修改
项目链接
- GitHub 仓库:https://github.com/baristikir/flutter-swift-documentscan
- 作者:Baris Tikir
- 许可证:MIT
分享: