flutterdebuggingdartflutter-runflutter-debug

How can I check if a Flutter application is running in debug?


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.

Something like this

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

How can I check if the Flutter application is running in debug or release mode?


Solution

  • 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.


    The easiest way is to use assert as it only runs in debug mode.

    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;
    }());
    

    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.