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

如何自定义Flutter Barcode Scanner扫码界面?

基于Flutter Barcode Scanner实现自定义扫码界面

默认的scanBarcode方法仅提供固定样式的扫码弹窗,要实现你需要的带自定义扫描框、顶部/底部UI的界面,需要使用该包提供的FlutterBarcodeScannerWidget组件构建自定义页面,而非调用快捷方法。

实现步骤及代码示例

  1. 确保你的flutter_barcode_scanner包版本支持FlutterBarcodeScannerWidget(建议使用最新稳定版)
  2. 通过Stack组件将扫描视图与自定义UI元素叠加,构建目标样式页面:
import 'package:flutter/material.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';

class CustomQrScanner extends StatefulWidget {
  const CustomQrScanner({Key? key}) : super(key: key);

  @override
  State<CustomQrScanner> createState() => _CustomQrScannerState();
}

class _CustomQrScannerState extends State<CustomQrScanner> {
  void _onBarcodeScanned(String barcode) {
    // 扫码成功后的逻辑,比如返回上一页传递结果
    Navigator.pop(context, barcode);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 核心扫描视图
          FlutterBarcodeScannerWidget(
            scanMode: ScanMode.QR,
            onScan: _onBarcodeScanned,
            lineColor: const Color(0xFF00FFB6),
            isShowFlashIcon: true,
          ),
          // 顶部返回按钮
          Positioned(
            top: 40,
            left: 20,
            child: IconButton(
              icon: const Icon(Icons.arrow_back, color: Colors.white, size: 30),
              onPressed: () => Navigator.pop(context),
            ),
          ),
          // 中间自定义扫描框
          Center(
            child: Container(
              width: 280,
              height: 280,
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF00FFB6), width: 2),
                borderRadius: BorderRadius.circular(12),
              ),
              child: const Center(
                // 可替换为扫描线动画
                child: SizedBox(
                  width: 260,
                  height: 2,
                  child: LinearProgressIndicator(
                    color: Color(0xFF00FFB6),
                    backgroundColor: Colors.transparent,
                  ),
                ),
              ),
            ),
          ),
          // 底部提示文字
          Positioned(
            bottom: 60,
            left: 0,
            right: 0,
            child: const Text(
              "将二维码放入框内,即可自动扫描",
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
        ],
      ),
    );
  }
}

关键说明

  • 用Stack实现扫描视图与自定义UI的层级叠加,保证扫描视图处于最底层
  • 通过FlutterBarcodeScannerWidget的onScan回调获取扫码结果,替代scanBarcode的异步返回逻辑
  • 扫描框的尺寸、样式可按需调整,还能添加扫描线动画增强交互感
  • 若需处理相机权限,可搭配permission_handler包在进入页面时提前申请权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:05:17