我正在寻找一种在应用程序处于调试模式时在Flutter中执行代码的方法。在颤振有可能吗?我在文件里找不到。

就像这样

If(app.inDebugMode) {
   print("Print only in debug mode");
}

如何检查Flutter应用程序是运行在调试模式还是发布模式?


当前回答

请使用Remi的答案与kReleaseMode和kDebugMode或Dart编译将无法树摇你的代码。


这个小片段应该做你需要的:

bool get isInDebugMode {
  bool inDebugMode = false;
  assert(inDebugMode = true);
  return inDebugMode;
}

如果不是,您可以配置IDE来启动不同的主程序。dart在调试模式,你可以设置一个布尔值。

其他回答

虽然这是可行的,但使用常量kReleaseMode或kDebugMode更可取。请参阅Rémi下面的完整解释,这应该是一个公认的问题。


最简单的方法是使用assert,因为它只在调试模式下运行。

下面是一个来自Flutter的Navigator源代码的例子:

assert(() {
  if (navigator == null && !nullOk) {
    throw new FlutterError(
      'Navigator operation requested with a context that does not include a Navigator.\n'
      'The context used to push or pop routes from the Navigator must be that of a '
      'widget that is a descendant of a Navigator widget.'
    );
  }
  return true;
}());

特别注意调用末尾的()- assert只能操作布尔值,因此仅仅传入一个函数是行不通的。

在以后的版本中,你可以使用kDebugMode:

if (kDebugMode)
  doSomething();

虽然在技术上可以使用断言手动创建“is调试模式”变量,但应该避免这样做。

相反,使用package:flutter/foundation.dart中的常量kReleaseMode


区别就在于摇树。

摇树(即编译器删除未使用的代码)依赖于变量是常量。

问题是,通过断言,我们的isInReleaseMode布尔值不是常量。所以在发布我们的应用时,开发代码和发布代码都包含在内。

另一方面,kReleaseMode是一个常量。因此,编译器能够正确地删除未使用的代码,我们可以安全地做:

if (kReleaseMode) {

} else {
  // Will be tree-shaked on release builds.
}

k调试模式

现在可以使用kDebugMode常量了。

if (kDebugMode) {
  // Code here will only be included in debug mode.
  // As kDebugMode is a constant, the tree shaker
  // will remove the code entirely from compiled code.
} else {

}

这比!kReleaseMode更可取,因为它也检查配置文件模式,即,kDebugMode表示不在发布模式和不在配置文件模式。

kReleaseMode

如果你只是想检查释放模式,而不是配置文件模式,你可以使用kReleaseMode代替:

if (kReleaseMode) {
  // Code here will only be run in release mode.
  // As kReleaseMode is a constant, the tree shaker
  // will remove the code entirely from other builds.
} else {

}

kProfileMode

如果你只是想检查配置文件模式,而不是发布模式,你可以使用kProfileMode代替:

if (kProfileMode) {
  // Code here will only be run in release mode.
  // As kProfileMode is a constant, the tree shaker
  // will remove the code entirely from other builds.
} else {

}

不要挑剔,但是基础包包含一个kDebugMode常量。

So:

import 'package:flutter/foundation.dart' as Foundation;

if(Foundation.kDebugMode) {
   print("App in debug mode");
}

请使用Remi的答案与kReleaseMode和kDebugMode或Dart编译将无法树摇你的代码。


这个小片段应该做你需要的:

bool get isInDebugMode {
  bool inDebugMode = false;
  assert(inDebugMode = true);
  return inDebugMode;
}

如果不是,您可以配置IDE来启动不同的主程序。dart在调试模式,你可以设置一个布尔值。