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

Flutter使用Stacked架构时如何调用错误消息弹窗函数实现扫码异常提示

Stacked架构下扫码失败弹窗实现方案

前置依赖配置

确认你已完成Stacked的基础服务注册,在全局依赖注入配置中添加DialogService注册:

final locator = GetIt.instance;
void setupLocator() {
  locator.registerLazySingleton(() => DialogService());
  // 其余原有服务注册逻辑保留
}

ViewModel逻辑层实现

按照Stacked的视图逻辑分离原则,扫码结果校验、弹窗调用逻辑统一放在ViewModel中处理:

class ScanViewModel extends BaseViewModel {
  final _dialogService = locator<DialogService>();

  // 处理扫码返回结果
  void handleScanResult(Barcode? scanResult) async {
    // 扫码失败校验逻辑,可根据业务需求调整判断条件
    if(scanResult == null || scanResult.code?.trim().isEmpty == true) {
      await _dialogService.showDialog(
        title: '扫码失败',
        description: '未识别到有效二维码,请调整拍摄角度、光线后重试',
        buttonTitle: '知道了'
      );
      return;
    }
    // 扫码成功后的业务逻辑自行补充
  }
}

UI层代码修改

调整你现有的ScanResult组件,绑定ViewModel并触发扫码结果处理逻辑,修改后完整代码如下:

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

  @override
  _ScanResultState createState() => _ScanResultState();
}

class _ScanResultState extends State<ScanResult> {
  Barcode? result;
  QRViewController? controller;

  final qrkey = GlobalKey(debugLabel: 'QR');
  
  // 扫码监听回调
  void _onScanInit(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
      });
      // 调用ViewModel处理扫码结果
      Provider.of<ScanViewModel>(context, listen: false).handleScanResult(result);
    });
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<ScanViewModel>.reactive(
      viewModelBuilder: () => ScanViewModel(),
      builder: (context, viewModel, child) => Container(
        padding: const EdgeInsets.all(5),
        decoration: const BoxDecoration(
          color: Colors.white24,
        ),
        child: Text(
          result != null ? '扫描结果: ${result!.code}' : '请对准二维码扫描',
          maxLines: 2,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 20,
          ),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
}

轻量替代方案

如果你暂时不想引入DialogService,也可以直接在UI层调用Flutter原生弹窗方法,在扫码回调的判断分支中添加如下代码即可:

if(result == null || result?.code?.isEmpty == true) {
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: const Text('扫码失败'),
      content: const Text('未识别到有效二维码,请重试'),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('确定')
        )
      ],
    )
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:36:10