You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用mobile_scanner扫码返回主页面时出现黑屏问题

解决Flutter mobile_scanner扫码后返回主页面黑屏问题

问题出在扫码页面的MobileScannerController没有在页面销毁时正确释放相机资源,导致返回主页面后相机仍在后台运行,引发全屏黑屏。以下是修复后的代码:

修改后的扫码页面代码

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

  @override
  State<ScannerScreen> createState() => _ScannerScreenState();
}

class _ScannerScreenState extends State<ScannerScreen> {
  // 将控制器设为类成员变量,方便后续释放资源
  final MobileScannerController _controller = MobileScannerController(
    detectionSpeed: DetectionSpeed.noDuplicates,
  );

  void _handleBarcode(BarcodeCapture barcodes) {
    final barcode = barcodes.barcodes.firstOrNull;
    if (barcode?.rawValue != null && mounted) {
      // 先暂停扫描,避免重复触发回调
      _controller.stop();
      // 直接返回扫码结果,无需更新当前页面UI
      Navigator.pop(context, barcode!.rawValue);
    }
  }

  @override
  void dispose() {
    // 页面销毁时释放控制器,彻底释放相机资源
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Scan Barcode'),
      ),
      body: Center(
        child: MobileScanner(
          controller: _controller,
          onDetect: _handleBarcode,
        ),
      ),
    );
  }
}

关键修复点

  • 将MobileScannerController声明为类成员变量,而非在build方法内临时创建,确保能在页面销毁时调用dispose()释放相机资源
  • 扫码成功后先调用_controller.stop()暂停扫描,防止onDetect被重复触发导致多次执行Navigator.pop
  • 去掉不必要的setState操作,因为扫码成功后页面会立即被弹出,无需更新当前页面的UI

调用扫码页面的代码无需修改,保持原样即可。

内容的提问来源于stack exchange,提问作者Mohammad Radwan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:40:01