如何检查Flutter应用程序是否在调试中运行? [英] How to check flutter application is running in debug?
问题描述
我有一个简短的问题.我正在寻找一种在应用程序处于调试模式时在Flutter中执行代码的方法.在Flutter中有可能吗?我似乎在文档的任何地方都找不到它.
I have a short question. I'm looking for a way to execute code in Flutter when the app is in Debug mode. Is that possible in Flutter? I can't seem to find it anywhere in the documentation.
类似这样的东西
If(app.inDebugMode) {
print("Print only in debug mode");
}
如何检查Flutter应用程序是否以调试或发布模式运行?
How to check if the flutter application is running in debug or release mode?
推荐答案
虽然可行,但最好使用常量kReleaseMode
或kDebugMode
.请参阅下面的Rémi的答案以了解完整的解释,这应该是公认的问题.
While this works, using constants kReleaseMode
or kDebugMode
is preferable. See Rémi's answer below for a full explanation, which should probably be the accepted question.
最简单的方法是使用assert
,因为它仅在调试模式下运行.
The easiest way is to use assert
as it only runs in debug mode.
这是Flutter的Navigator源代码中的一个示例:
Here's an example from Flutter's Navigator source code:
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只能对布尔值进行操作,因此仅传入函数是行不通的.
Note in particular the ()
at the end of the call - assert can only operate on a boolean, so just passing in a function doesn't work.
这篇关于如何检查Flutter应用程序是否在调试中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!