flutterdartoptimization

Inline debug print in Flutter


I am writting an application in Flutter using Dart. I want to keep a few 'prints' here and there, but I don't want them in the release version of my app (I want them completely gone, not keeping an if condition there).

I have written the following class and method:

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

class DebugPrinter {
  @pragma("vm:always-consider-inlining")
  static void print(Object? object) {
    if(!kReleaseMode){
      core.print(object);
    }
  }
}

The idea is to use kReleaseMode as explained in this StackOverflow question, to ensure that the if condition is constant at compile time: How can I check if a Flutter application is running in debug?

Then using the @pragma("vm:always-consider-inlining") to attempt forcing the builder to inline the function.

Then I use it wherever I want: DebugPrinter.print('Send button pressed.').

My expectation is that the whole construct results in absolutely no code for release builds. Is it correct on paper? How can I verify it in practice? Is there another way to achieve the same goal (having a piece of functionality completely disappear in release/debug)?


Solution

  • My expectation is that the whole construct results in absolutely no code for release builds.

    No, this code will be partially compiled for release mode, that is because, the conditional kReleaseMode is a constant, i.e it can be checked during compile time. kReleaseMode constant indicates to the compiler that the following code will not be executed in Release mode and is safe to be removed from release builds

    Compiled code:

    class DebugPrinter {
      static void print(Object? object) {
        // Do nothing
      }
    }
    

    Is there another way to achieve the same goal (having a piece of functionality completely disappear in release/debug)?

    using an if(!kReleaseMode) with debugPrint would be the best approach imo

    Read more about it Here