Flutter中如何检测开发者选项的启用与禁用状态?
在Flutter中检测系统开发者模式并展示限制页面
由于Flutter框架本身没有提供直接读取系统开发者模式状态的API,你需要通过MethodChannel与原生平台(Android/iOS)交互来实现该功能,以下是具体实现步骤:
Android端实现
在Flutter项目的android/app/src/main/kotlin/[包名]/MainActivity.kt中注册MethodChannel,并实现获取开发者模式状态的逻辑:
import android.provider.Settings import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { private val CHANNEL = "com.example/dev_mode_check" override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> if (call.method == "isDeveloperModeEnabled") { val devModeEnabled = try { Settings.Global.getInt(contentResolver, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) == 1 } catch (e: Settings.SettingNotFoundException) { false } result.success(devModeEnabled) } else { result.notImplemented() } } } }
Flutter端实现
在Dart代码中创建MethodChannel实例,调用原生接口并根据状态切换页面:
import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { static const MethodChannel _channel = MethodChannel('com.example/dev_mode_check'); bool _isDeveloperModeEnabled = false; @override void initState() { super.initState(); _checkDeveloperMode(); } Future<void> _checkDeveloperMode() async { bool isEnabled; try { isEnabled = await _channel.invokeMethod('isDeveloperModeEnabled') ?? false; } on PlatformException catch (_) { isEnabled = false; } setState(() { _isDeveloperModeEnabled = isEnabled; }); } @override Widget build(BuildContext context) { return MaterialApp( home: _isDeveloperModeEnabled ? const DeveloperRestrictionPage() : const HomePage(), ); } } // 开发者模式限制页面 class DeveloperRestrictionPage extends StatelessWidget { const DeveloperRestrictionPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text( '开发者模式已开启,该应用暂时无法使用', style: Theme.of(context).textTheme.headlineSmall, textAlign: TextAlign.center, ), ), ); } } // 正常首页 class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('应用首页')), body: const Center(child: Text('正常使用中')), ); } }
补充说明
- Android端通过
Settings.Global.getInt读取系统状态,返回1表示开发者模式开启,0表示关闭;捕获SettingNotFoundException避免异常崩溃。 - Flutter端在页面初始化时调用原生接口,根据返回结果自动切换显示限制页面或正常首页。
- 若需支持iOS平台,可在iOS原生项目的
AppDelegate.swift中实现对应逻辑:通过检测系统开发者模式相关的UserDefaults键值或调用iOS系统API完成状态判断。
内容的提问来源于stack exchange,提问作者Naimish Patel
相关产品推荐
相关产品推荐

