flutter_integrated_whb/lib/pages/home/study/face_ecognition_page.dart

476 lines
14 KiB
Dart
Raw Normal View History

2025-07-17 16:10:46 +08:00
import 'dart:async';
2025-09-15 15:54:03 +08:00
import 'dart:io';
import 'package:flutter/services.dart';
2025-07-17 16:10:46 +08:00
import 'package:camera/camera.dart';
2025-09-15 15:54:03 +08:00
import 'package:flutter/foundation.dart';
2025-07-17 16:10:46 +08:00
import 'package:flutter/material.dart';
2025-09-15 15:54:03 +08:00
import 'package:permission_handler/permission_handler.dart' as ph;
import 'package:qhd_prevention/customWidget/custom_alert_dialog.dart';
2025-07-17 16:10:46 +08:00
import 'package:qhd_prevention/customWidget/custom_button.dart';
2025-07-18 17:13:38 +08:00
import 'package:qhd_prevention/customWidget/toast_util.dart';
2025-09-15 15:54:03 +08:00
import 'package:qhd_prevention/http/ApiService.dart';
2025-07-17 16:10:46 +08:00
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/tools/tools.dart';
2025-09-15 15:54:03 +08:00
// 在类最上面State 内)加入一个 channel 常量
const MethodChannel _platformChan = MethodChannel('qhd_prevention/permissions');
2025-07-17 16:10:46 +08:00
/// 人脸识别模式
2025-09-18 15:40:01 +08:00
enum FaceMode { setUpdata, study, scan }
2025-07-17 16:10:46 +08:00
class FaceRecognitionPage extends StatefulWidget {
final String studentId;
2025-09-18 15:40:01 +08:00
final Map data;
2025-07-17 16:10:46 +08:00
final FaceMode mode;
const FaceRecognitionPage({
Key? key,
2025-07-18 17:13:38 +08:00
required this.studentId,
2025-09-18 15:40:01 +08:00
required this.data,
this.mode = FaceMode.study,
2025-07-17 16:10:46 +08:00
}) : super(key: key);
@override
_FaceRecognitionPageState createState() => _FaceRecognitionPageState();
}
2025-09-15 15:54:03 +08:00
class _FaceRecognitionPageState extends State<FaceRecognitionPage>
with WidgetsBindingObserver {
2025-07-17 16:10:46 +08:00
CameraController? _cameraController;
Timer? _timer;
int _attempts = 0;
static const int _maxAttempts = 8;
static const Duration _interval = Duration(seconds: 2);
2025-09-15 15:54:03 +08:00
String _errMsg = '';
2025-09-18 15:40:01 +08:00
bool get _isManualMode => widget.mode == FaceMode.setUpdata;
2025-07-17 16:10:46 +08:00
2025-09-15 15:54:03 +08:00
bool _isInitializing = false;
bool _isTaking = false;
2025-07-17 16:10:46 +08:00
@override
void initState() {
super.initState();
2025-09-15 15:54:03 +08:00
WidgetsBinding.instance.addObserver(this);
// 延迟到首帧渲染后再请求权限并初始化相机,避免 iOS 在还未准备好时错过系统弹窗
WidgetsBinding.instance.addPostFrameCallback((_) {
_initCameraWithPermission();
});
2025-07-17 16:10:46 +08:00
}
@override
void dispose() {
2025-09-15 15:54:03 +08:00
WidgetsBinding.instance.removeObserver(this);
2025-07-17 16:10:46 +08:00
_timer?.cancel();
2025-09-15 15:54:03 +08:00
try {
_cameraController?.dispose();
} catch (_) {}
2025-07-17 16:10:46 +08:00
super.dispose();
}
2025-09-15 15:54:03 +08:00
// 生命周期:后台/前台切换时处理相机释放/恢复
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (_cameraController == null || !_cameraController!.value.isInitialized) {
return;
}
if (state == AppLifecycleState.inactive) {
// 可选:释放相机,节省资源
try {
_cameraController?.dispose();
2025-09-18 21:45:41 +08:00
Navigator.pop(context);
2025-09-15 15:54:03 +08:00
} catch (_) {}
_cameraController = null;
} else if (state == AppLifecycleState.resumed) {
// 恢复时重新初始化相机(并会再次请求权限)
if (!_isInitializing) {
_initCameraWithPermission();
}
2025-07-17 16:10:46 +08:00
}
}
2025-09-15 15:54:03 +08:00
/// 请求 camera 权限iOS优先走原生 AVCaptureDevice.requestAccessAndroid使用 permission_handler
Future<bool> _requestCameraPermission() async {
try {
// iOS使用原生 API 强制唤起系统授权弹窗
if (Platform.isIOS) {
try {
final dynamic res = await _platformChan.invokeMethod('requestCameraAccess');
// 原生返回 true/false
if (res == true) {
debugPrint('[FaceRecognition] iOS native camera access granted');
return true;
} else {
debugPrint('[FaceRecognition] iOS native camera access denied');
// 如果被拒绝(非永久还是永久都返回 false再根据 permission_handler 的状态做后续提示/引导
final status = await ph.Permission.camera.status;
if (status.isPermanentlyDenied) {
await _showPermissionDialog(permanent: true);
} else {
await _showPermissionDialog(permanent: false);
}
return false;
}
} on PlatformException catch (e) {
debugPrint('[FaceRecognition] platform channel error: $e — fallback to permission_handler');
// 如果 platform channel 异常,回退到 permission_handler
}
}
// 非 iOS 或 platform 调用失败时走 permission_handler保证 Android 正常)
final result = await ph.Permission.camera.request();
debugPrint('[FaceRecognition] permission_handler camera result: $result');
if (result.isGranted) return true;
if (result.isPermanentlyDenied) {
await _showPermissionDialog(permanent: true);
return false;
}
if (result.isDenied) {
await _showPermissionDialog(permanent: false);
return false;
}
if (result.isRestricted) {
if (mounted) ToastUtil.showNormal(context, '相机权限受限,无法使用本功能');
return false;
}
if (result.isLimited) {
if (mounted) ToastUtil.showNormal(context, '相机权限受限limited');
return false;
}
return false;
} catch (e) {
debugPrint('[FaceRecognition] permission request error: $e');
if (mounted) ToastUtil.showNormal(context, '请求相机权限时出错');
return false;
}
}
/// 显示权限被拒/永久拒绝对话框(区分 permanent
Future<void> _showPermissionDialog({required bool permanent}) async {
if (!mounted) return;
await CustomAlertDialog.showConfirm(
context,
title: '需要相机权限',
content:
permanent
? '检测到相机权限已被永久拒绝,请到系统设置中打开相机权限以继续使用人脸识别功能。'
: '相机权限被拒绝,是否重试或前往设置打开权限?',
cancelText: '取消',
onConfirm: () async {
try {
final retry = await ph.Permission.camera.request();
debugPrint('[FaceRecognition] retry request result: $retry');
if (retry.isGranted) {
if (mounted) await _initCamera();
} else if (retry.isPermanentlyDenied) {
try {
await ph.openAppSettings();
} catch (e) {
debugPrint('[FaceRecognition] openAppSettings error: $e');
if (mounted) ToastUtil.showNormal(context, '无法打开设置,请手动前往系统设置授权');
}
} else {
if (mounted) ToastUtil.showNormal(context, '相机权限未授予');
}
} catch (e) {
debugPrint('[FaceRecognition] retry request error: $e');
}
},
2025-07-18 17:13:38 +08:00
);
}
2025-09-15 15:54:03 +08:00
/// 初始化:先请求权限,再打开相机
Future<void> _initCameraWithPermission() async {
if (!mounted) return;
final ok = await _requestCameraPermission();
if (!ok) return;
await _initCamera();
2025-07-18 17:13:38 +08:00
}
2025-09-15 15:54:03 +08:00
Future<void> _initCamera() async {
if (_isInitializing) return;
_isInitializing = true;
try {
final cams = await availableCameras();
CameraDescription? front;
2025-07-18 17:13:38 +08:00
try {
2025-09-15 15:54:03 +08:00
front = cams.firstWhere(
(c) => c.lensDirection == CameraLensDirection.front,
);
2025-07-18 17:13:38 +08:00
} catch (_) {
2025-09-15 15:54:03 +08:00
if (cams.isNotEmpty) front = cams.first;
}
if (front == null) {
if (!mounted) return;
ToastUtil.showError(context, '未检测到可用摄像头');
_isInitializing = false;
return;
}
_cameraController = CameraController(
front,
ResolutionPreset.medium,
enableAudio: false,
imageFormatGroup: ImageFormatGroup.yuv420,
);
await _cameraController!.initialize();
// 尽量关闭闪光
try {
await _cameraController!.setFlashMode(FlashMode.off);
} catch (_) {}
if (!mounted) return;
setState(() {});
2025-07-17 16:10:46 +08:00
2025-09-15 15:54:03 +08:00
// 启动自动拍照定时器(若为自动模式)
_timer?.cancel();
_attempts = 0;
if (!_isManualMode) {
_timer = Timer.periodic(_interval, (_) => _captureAndUpload());
2025-07-17 16:10:46 +08:00
}
2025-09-15 15:54:03 +08:00
} catch (e, st) {
debugPrint('[FaceRecognition] init camera error: $e\n$st');
if (mounted) {
ToastUtil.showError(context, '初始化摄像头失败');
}
} finally {
_isInitializing = false;
2025-07-17 16:10:46 +08:00
}
}
2025-09-15 15:54:03 +08:00
/// 自动模式:定时拍照并上传
Future<void> _captureAndUpload() async {
if (_isManualMode) return;
if (_cameraController == null || !_cameraController!.value.isInitialized)
return;
if (_attempts >= _maxAttempts) return _onTimeout();
if (_isTaking) return;
_isTaking = true;
_attempts++;
try {
try {
await _cameraController!.setFlashMode(FlashMode.off);
} catch (_) {}
final XFile pic = await _cameraController!.takePicture();
2025-09-18 15:40:01 +08:00
var res = {};
switch(widget.mode) {
case FaceMode.study:
res = await ApiService.getStudyUserFace(pic.path, widget.data);
break;
case FaceMode.setUpdata:
res = await ApiService.getUpdataUserFace(pic.path, widget.data);
break;
case FaceMode.scan:
res = await ApiService.getScanUserFace(pic.path, widget.data);
break;
}
2025-09-15 15:54:03 +08:00
if (res['result'] == 'success') {
_onSuccess();
} else {
if (!mounted) return;
setState(() {
_errMsg = (res['msg'] ?? '').toString();
});
}
} catch (e, st) {
debugPrint('[FaceRecognition] capture error: $e\n$st');
// 忽略单次异常,等待下一次尝试
} finally {
_isTaking = false;
}
}
/// 手动拍照并上传
2025-07-17 16:10:46 +08:00
Future<void> _captureAndReload() async {
2025-09-15 15:54:03 +08:00
if (_cameraController == null || !_cameraController!.value.isInitialized)
return;
if (_isTaking) return;
_isTaking = true;
2025-07-18 17:13:38 +08:00
_showLoading();
2025-09-15 15:54:03 +08:00
2025-07-17 16:10:46 +08:00
try {
2025-09-15 15:54:03 +08:00
// 再次确认 camera 权限(以防用户运行时撤销)
final status = await ph.Permission.camera.status;
if (!status.isGranted) {
final ok = await _requestCameraPermission();
if (!ok) {
_hideLoading();
_isTaking = false;
return;
}
}
try {
await _cameraController!.setFlashMode(FlashMode.off);
} catch (_) {}
final XFile pic = await _cameraController!.takePicture();
2025-07-18 17:13:38 +08:00
final res = await ApiService.reloadMyFace(pic.path, widget.studentId);
2025-09-15 15:54:03 +08:00
2025-07-18 17:13:38 +08:00
_hideLoading();
2025-09-15 15:54:03 +08:00
2025-07-17 16:10:46 +08:00
if (res['result'] == 'success') {
_onSuccess();
} else {
2025-07-18 17:13:38 +08:00
ToastUtil.showError(context, '验证失败,请重试');
2025-07-17 16:10:46 +08:00
}
2025-09-15 15:54:03 +08:00
} catch (e, st) {
debugPrint('[FaceRecognition] manual capture error: $e\n$st');
2025-07-18 17:13:38 +08:00
_hideLoading();
2025-09-15 15:54:03 +08:00
ToastUtil.showError(context, '拍照失败,请重试');
} finally {
_isTaking = false;
2025-07-17 16:10:46 +08:00
}
}
void _onSuccess() {
_timer?.cancel();
2025-09-18 15:40:01 +08:00
if (widget.mode == FaceMode.setUpdata) {
2025-07-18 17:13:38 +08:00
ToastUtil.showSuccess(context, '已更新人脸信息');
2025-09-15 15:54:03 +08:00
Future.delayed(const Duration(milliseconds: 800), () {
if (mounted) Navigator.of(context).pop(true);
});
2025-07-18 17:13:38 +08:00
return;
}
2025-09-15 15:54:03 +08:00
Future.delayed(const Duration(milliseconds: 800), () {
if (mounted) Navigator.of(context).pop(true);
});
2025-07-17 16:10:46 +08:00
}
void _onTimeout() {
_timer?.cancel();
2025-07-18 17:13:38 +08:00
ToastUtil.showError(context, '人脸超时,请重新识别!');
2025-09-15 15:54:03 +08:00
Future.delayed(const Duration(seconds: 3), () {
if (mounted) Navigator.of(context).pop(false);
});
}
void _showLoading() {
if (!mounted) return;
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => const Center(child: CircularProgressIndicator()),
);
}
void _hideLoading() {
if (!mounted) return;
if (Navigator.canPop(context)) Navigator.pop(context);
2025-07-17 16:10:46 +08:00
}
2025-07-18 17:13:38 +08:00
void _showToast(String msg) {
ToastUtil.showNormal(context, msg);
}
2025-07-17 16:10:46 +08:00
@override
Widget build(BuildContext context) {
if (_cameraController == null || !_cameraController!.value.isInitialized) {
return const Scaffold(
backgroundColor: Colors.white,
body: Center(child: CircularProgressIndicator()),
);
}
2025-09-15 15:54:03 +08:00
2025-07-17 16:10:46 +08:00
final previewSize = _cameraController!.value.previewSize!;
final previewAspect = previewSize.height / previewSize.width;
final radius = (screenWidth(context) - 100) / 2;
return Scaffold(
backgroundColor: Colors.white,
2025-09-15 15:54:03 +08:00
appBar: const MyAppbar(title: '人脸识别'),
2025-07-17 16:10:46 +08:00
body: Stack(
children: [
Positioned.fill(child: Container(color: Colors.white)),
Transform.translate(
offset: const Offset(0, -100),
child: Stack(
children: [
Center(
child: ClipOval(
child: AspectRatio(
aspectRatio: previewAspect,
child: CameraPreview(_cameraController!),
),
),
),
Positioned.fill(
child: CustomPaint(
painter: _WhiteMaskPainter(radius: radius),
),
),
],
),
),
Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.only(top: 250),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
2025-09-15 15:54:03 +08:00
const Text(
2025-07-18 17:13:38 +08:00
'请将人脸置于圆圈内',
2025-09-15 15:54:03 +08:00
style: TextStyle(fontSize: 16, color: Colors.black87),
2025-08-29 20:33:23 +08:00
textAlign: TextAlign.center,
),
2025-09-15 15:54:03 +08:00
if (_errMsg.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 6.0),
child: Text(
_errMsg,
style: const TextStyle(fontSize: 14, color: Colors.red),
textAlign: TextAlign.center,
),
),
2025-07-17 16:10:46 +08:00
const SizedBox(height: 20),
if (_isManualMode)
2025-09-15 15:54:03 +08:00
CustomButton(
text: '拍照/上传',
backgroundColor: Colors.blue,
onPressed: _captureAndReload,
),
2025-07-17 16:10:46 +08:00
],
),
),
),
],
),
);
}
}
class _WhiteMaskPainter extends CustomPainter {
final double radius;
2025-09-15 15:54:03 +08:00
2025-07-17 16:10:46 +08:00
_WhiteMaskPainter({required this.radius});
@override
void paint(Canvas canvas, Size size) {
canvas.saveLayer(Offset.zero & size, Paint());
canvas.drawRect(Offset.zero & size, Paint()..color = Colors.white);
canvas.drawCircle(
size.center(Offset.zero),
radius,
Paint()..blendMode = BlendMode.clear,
);
canvas.restore();
}
@override
bool shouldRepaint(covariant CustomPainter old) => false;
}