camera_scanner 0.0.3
camera_scanner: ^0.0.3 copied to clipboard
A Flutter Windows plugin for camera preview and barcode/QR code scanning using Media Foundation and ZXing-C++.
example/lib/main.dart
import 'dart:async';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_scanner/camera_scanner.dart';
import 'package:camera_scanner_example/scan_overlay.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
debugShowCheckedModeBanner: false,
home: CameraScannerExample(),
));
}
class CameraScannerExample extends StatefulWidget {
const CameraScannerExample({super.key});
@override
State<CameraScannerExample> createState() => _CameraScannerExampleState();
}
class _CameraScannerExampleState extends State<CameraScannerExample> {
final CameraScanner _scanner = CameraScanner();
List<CameraDescription> _cameras = <CameraDescription>[];
int _selectedCameraIndex = 0;
int _cameraId = -1;
bool _isInitialized = false;
Size? _previewSize;
String _statusMessage = '正在检测相机...';
String _lastScanResult = '暂无扫码结果';
DateTime? _lastScanTime;
StreamSubscription<CameraErrorEvent>? _errorSubscription;
StreamSubscription<CameraClosingEvent>? _closingSubscription;
StreamSubscription<String>? _scanSubscription;
final double _cropRatio = 0.5;
@override
void initState() {
super.initState();
_initCameras();
}
@override
void dispose() {
_disposeCurrentCamera();
super.dispose();
}
Future<void> _initCameras() async {
try {
final List<CameraDescription> cameras = await _scanner.availableCameras();
if (!mounted) return;
if (cameras.isEmpty) {
setState(() {
_statusMessage = '未检测到可用摄像头';
});
return;
}
setState(() {
_cameras = cameras;
_selectedCameraIndex = 0;
});
await _startCamera(_selectedCameraIndex);
} catch (e) {
if (!mounted) return;
setState(() {
_statusMessage = '获取摄像头失败: $e';
});
}
}
Future<void> _startCamera(int index) async {
if (_cameras.isEmpty || index < 0 || index >= _cameras.length) return;
await _disposeCurrentCamera();
final CameraDescription camera = _cameras[index];
setState(() {
_statusMessage = '正在打开相机: ${camera.name}...';
_isInitialized = false;
});
try {
final int cameraId = await _scanner.createCameraWithSettings(
camera,
const MediaSettings(
resolutionPreset: ResolutionPreset.high,
fps: 30,
enableAudio: false,
),
);
_errorSubscription = _scanner.onCameraError(cameraId).listen((event) {
if (!mounted) return;
setState(() {
_statusMessage = '相机错误: ${event.description}';
});
});
_closingSubscription = _scanner.onCameraClosing(cameraId).listen((_) {
if (!mounted) return;
setState(() {
_statusMessage = '相机已关闭';
});
});
// 监听扫码流
_scanSubscription = _scanner.onScan(cameraId).listen((String code) {
if (!mounted) return;
setState(() {
_lastScanResult = code;
_lastScanTime = DateTime.now();
});
});
final Future<CameraInitializedEvent> initFuture =
_scanner.onCameraInitialized(cameraId).first;
await _scanner.initializeCamera(cameraId, ratio: _cropRatio);
final CameraInitializedEvent initEvent = await initFuture;
if (!mounted) return;
setState(() {
_cameraId = cameraId;
_isInitialized = true;
_previewSize = Size(initEvent.previewWidth, initEvent.previewHeight);
_statusMessage = '相机就绪: ${camera.name} (${initEvent.previewWidth.toInt()}x${initEvent.previewHeight.toInt()})';
});
} catch (e) {
if (!mounted) return;
setState(() {
_statusMessage = '启动相机失败: $e';
_isInitialized = false;
_cameraId = -1;
});
}
}
Future<void> _disposeCurrentCamera() async {
await _errorSubscription?.cancel();
_errorSubscription = null;
await _closingSubscription?.cancel();
_closingSubscription = null;
await _scanSubscription?.cancel();
_scanSubscription = null;
if (_cameraId >= 0) {
final int idToDispose = _cameraId;
_cameraId = -1;
_isInitialized = false;
try {
await _scanner.dispose(idToDispose);
} catch (e) {
debugPrint('释放相机异常: $e');
}
}
}
void _switchCamera() {
if (_cameras.length <= 1) return;
final int nextIndex = (_selectedCameraIndex + 1) % _cameras.length;
setState(() {
_selectedCameraIndex = nextIndex;
});
_startCamera(nextIndex);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF1E1E1E),
appBar: AppBar(
title: const Text('Windows 相机扫码演示'),
backgroundColor: Colors.black87,
actions: [
if (_cameras.length > 1)
IconButton(
icon: const Icon(Icons.switch_camera),
tooltip: '切换相机',
onPressed: _switchCamera,
),
],
),
body: Column(
children: [
// 相机预览区
Expanded(
child: Center(
child: (_isInitialized && _cameraId >= 0 && _previewSize != null)
? AspectRatio(
aspectRatio: _previewSize!.width / _previewSize!.height,
child: Stack(
fit: StackFit.expand,
children: [
_scanner.buildPreview(_cameraId),
ScanOverlay(
imgWidth: _previewSize!.width,
rate: _cropRatio,
),
],
),
)
: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 16),
Text(
_statusMessage,
style: const TextStyle(color: Colors.white70),
),
],
),
),
),
// 扫码结果展示卡片
Container(
padding: const EdgeInsets.all(16.0),
color: Colors.black87,
child: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
const Icon(Icons.qr_code_scanner, color: Colors.lightBlueAccent),
const SizedBox(width: 8),
const Text(
'扫码结果',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
if (_lastScanTime != null)
Text(
'${_lastScanTime!.hour.toString().padLeft(2, '0')}:${_lastScanTime!.minute.toString().padLeft(2, '0')}:${_lastScanTime!.second.toString().padLeft(2, '0')}',
style: const TextStyle(color: Colors.white38, fontSize: 12),
),
],
),
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFF2A2A2A),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.white12),
),
child: SelectableText(
_lastScanResult,
style: TextStyle(
color: _lastScanTime != null ? Colors.greenAccent : Colors.white60,
fontSize: 15,
fontFamily: 'monospace',
),
),
),
const SizedBox(height: 6),
Text(
_statusMessage,
style: const TextStyle(color: Colors.white38, fontSize: 12),
textAlign: TextAlign.center,
),
],
),
),
),
],
),
);
}
}