Search code examples
dartflutterdart2js

How to exclude debug code


Let's say I have simple logger:

void main() {
  var logger = new MyLogger();
  logger.log("hello Dart");
}

I want this code to run in the dev mode (VM checked mode) but i don't want it in my production code. And i want it to be "tree shaked" away with the dart2js compiler. Is there some standard way?


Solution

  • You could embed the code in an assert. Assertions are ignored in production code and I'm sure not built to JS when pub build is run in release mode.

    class X {
      X() {
        print('x created');
      }
    
      void log(String m) {
        print(m);
      }
    }
    
    bool log(String m) {
      new X()..log(m);
          return true;
    }
    
    void main() {
      assert(() {
        new X()..log('in Assert');
        return true;
      });
    
      assert(() => log('in Assert')); // use a wrapper function
    }
    

    When you create a wrapper method that returns true than you don't have to do it explicit each time.

    You can also take a look at this question How to achieve precompiler directive like functionality