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

Flutter应用中BluetoothAdapter.getDefaultAdapter()已废弃引发编译失败问题求助

解决permission_handler 6.1.3中BluetoothAdapter.getDefaultAdapter()废弃导致的编译错误

嘿,这个问题我之前帮不少开发者解决过,其实根源很明确,咱们一步步来搞定它:

问题原因

你遇到的编译失败,本质是两个因素叠加的结果:

  1. 你使用的permission_handler:6.1.3版本里,ServiceManager.java中的isBluetoothServiceEnabled()方法调用了Android SDK已废弃的BluetoothAdapter.getDefaultAdapter()方法,触发了 deprecation 警告;
  2. 你的Android项目开启了-Werror编译选项——这个选项会把所有代码警告直接当作错误处理,所以原本的警告直接导致编译失败。

解决方案(按推荐程度排序)

1. 升级permission_handler到最新稳定版(最推荐)

新版本的permission_handler已经修复了这个废弃API的问题,完全规避了这类警告。你只需要修改pubspec.yaml里的依赖版本:

dependencies:
  permission_handler: ^10.2.0 # 可以替换成当前官网的最新稳定版

然后执行命令更新依赖:

flutter pub get

重新编译项目,这个问题就会直接消失。

2. 临时关闭-Werror编译选项(应急用)

如果你暂时没法升级依赖,可以先关闭警告转错误的设置:

  • 打开项目根目录下的android/build.gradle文件;
  • 在android代码块里找到compileOptions(没有的话就添加),移除或注释掉-Werror参数:
    android {
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
            // 移除下面这行,或者用//注释掉
            // options.compilerArgs << "-Werror"
        }
    }
    
  • 同步Gradle配置后重新编译项目即可。不过这个方法只是临时规避,长期来看还是建议升级依赖,避免后续更多废弃API的问题。

3. 手动修改permission_handler源码(不推荐)

如果因为特殊原因不能升级或修改gradle配置,也可以临时修改缓存里的源码:

  • 找到报错的文件:/Users/sumeetpujari/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-6.1.3/android/src/main/java/com/baseflow/permissionhandler/ServiceManager.java;
  • 把isBluetoothServiceEnabled()方法替换成使用新API的版本:
    @SuppressLint("MissingPermission")
    private boolean isBluetoothServiceEnabled() {
        // 用BluetoothManager获取适配器替代废弃的getDefaultAdapter()
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled();
    }
    

⚠️ 注意:这种修改会在你执行flutter pub get或清理Flutter缓存时被覆盖,只适合短期应急。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 02:02:29