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

Flutter/Dart是否有类似编译器开关的机制判断Debug构建?

无需手动传参的Debug代码实现方案

你完全不用自定义DEBUG标识,直接用Flutter框架内置的kDebugMode常量就行,它会自动识别当前构建模式,省去每次手动加--dart-define的麻烦。

改造后的代码

import 'dart:developer';
import 'package:flutter/foundation.dart';

void main() {
  if (kDebugMode) {
    log('This message will only be printed in debug mode');
  }

  // 其他在Debug和Release模式都运行的代码
}

为什么更省心?

  • kDebugMode是Flutter官方提供的常量,Debug构建时自动为true,Release/Profile构建时自动为false,完全不需要手动在构建命令里加额外参数。
  • 代码可读性更高,一眼就能看出这是Debug专属逻辑,比自定义的#if DEBUG更符合Flutter生态的常规写法。

补充说明

如果需要更细粒度的模式判断,还可以用kReleaseMode(仅Release模式生效)或kProfileMode(仅Profile模式生效),用法和kDebugMode一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:52:01