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

Flutter集成honeywell_scanner时WidgetsBinding与回调相关错误

Honeywell Scanner 集成错误修复

问题场景

集成honeywell_scanner包后,使用官方示例代码时,新Flutter项目的scan.dart文件出现三处错误,相关代码片段如下:

import 'package:flutter/material.dart';
import 'package:honeywell_scanner/honeywell_scanner.dart';

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

  @override
  State<Scan> createState() => _ScanState();
}

class _ScanState extends State<Scan> {
//...//
@override
  initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); //错误:参数类型'_ScanState'无法分配给参数类型'WidgetsBindingObserver'。
    honeywellScanner.scannerCallback = this; //错误:类型'_ScanState'的值无法分配给类型'ScannerCallback'的变量。
    initialize();
  }

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state); //错误:父类没有名为'didChangeAppLifecycleState'的方法。
    switch (state) {
      case AppLifecycleState.resumed:
        honeywellScanner.resumeScanner();
        break;
      case AppLifecycleState.inactive:
        honeywellScanner.pauseScanner();
        break;
      case AppLifecycleState
          .paused: //AppLifecycleState.paused用作停止状态,因为deactivate()更像是生命周期的暂停
        honeywellScanner.pauseScanner();
        break;
      case AppLifecycleState.detached:
        honeywellScanner.pauseScanner();
        break;
      default:
        break;
    }
  }
  //...//

错误修复方案

1. 修复「参数类型'_ScanState'无法分配给参数类型'WidgetsBindingObserver'」

让_ScanState类混入WidgetsBindingObserver,修改类定义:

class _ScanState extends State<Scan> with WidgetsBindingObserver {
  // ... 原有代码
}

2. 修复「类型'_ScanState'的值无法分配给类型'ScannerCallback'的变量」

让_ScanState实现ScannerCallback接口,并实现接口要求的两个方法:

class _ScanState extends State<Scan> with WidgetsBindingObserver implements ScannerCallback {
  // ... 原有代码

  @override
  void onDecoded(String? result) {
    // 在这里添加扫描结果的处理逻辑
  }

  @override
  void onError(Exception error) {
    // 在这里添加扫描错误的处理逻辑
  }
}

3. 修复「父类没有名为'didChangeAppLifecycleState'的方法」

didChangeAppLifecycleState是WidgetsBindingObserver接口的方法,父类State并没有这个方法,直接删除super.didChangeAppLifecycleState(state);这一行即可:

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  // 移除super调用
  switch (state) {
    // ... 原有状态处理逻辑
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:57:46