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

就像这样

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

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


当前回答

不要挑剔,但是基础包包含一个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在调试模式,你可以设置一个布尔值。

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

So:

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

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

虽然这是可行的,但使用常量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只能操作布尔值,因此仅仅传入一个函数是行不通的。

摘自Dart文档:

断言到底在什么时候起作用?这取决于工具和 你正在使用的框架: Flutter在调试模式下启用断言。 仅用于开发的工具(如dartdevc)通常默认启用断言。 有些工具,如dart和dart2js,通过命令行标志——enable- assertions来支持断言。 在产品代码中,断言将被忽略,而参数将被忽略 Assert没有被求值。

这里有一个简单的解决方案:

import 'package:flutter/foundation.dart';

然后你可以使用kReleaseMode like

if(kReleaseMode){ // Is Release Mode??
    print('release mode');
} else {
    print('debug mode');
}