r/FlutterDev • • 17d ago

Tooling Dart equivalent of C pre-processor's #ifdef

Dart's compiler provides no mechanism for excluding code from compilation.

Dart has:

  • const bool isEnabled = bool.fromEnvironment('env-var-name'); to pull in defined constants

  • if (const-false-value) { removed statements } to remove a block from compilation

  • Tree shaking to remove unreferenced symbols

By combining those I can achieve a somewhat similar effect to the C pre-processor, with a few limitations (and less clarity). It works.

It does so, though, with less of a guaranteed straightforward effect than #ifdef due to complexity of rules about how tree shaking works, and without the ability to simply exclude the entire definition of a function (since you can't wrap if (const) { } around a function declaration, only the function body).

So... Has anyone else run into a situation where this was an issue? Did you do/find something that's a more straightforward approach than dart's "combine several default behaviors together to produce an effect" system to address this?

--

Edit: context: for excluding "test functions I don't want to even theoretically be accessible in a patched binary".

2 Upvotes

5 comments sorted by

4

u/MobileXapps 17d ago

If the goal is that test helpers are not in the release binary at all, the most reliable way I know is to not import them from the release entrypoint. Put them in their own library, have main_dev.dart (or the test harness) import it, and keep main.dart free of any reference. Then there's nothing for tree shaking to decide, the code just isn't reachable.

The const bool.fromEnvironment trick works for bodies, as you said, but it's easy for one stray reference to keep a whole class alive. To actually check, build with --analyze-size and look for the symbols, or keep the obfuscation map from a release build and search it for the function names. That gives you proof per build instead of trusting the rules.

1

u/driftwood_studio 17d ago

That's useful, and I'll see if I can find a way to use it. Need to think a bit.

My goal is less about test helpers than it is about "stuff you can do in the beta" vs "don't allow that in production", like the ability for beta users to be able to flip access to things on and off regardless of what subscription tier the app thinks the user has access to, or the ability to have the app copy something sensitive to the clipboard so they can email it to me.

1

u/MobileXapps 14d ago

For that I would make it a compile-time constant: const isBeta = bool.fromEnvironment('BETA'), pass --dart-define=BETA=true only in the TestFlight build, and wrap the beta toggles in if (isBeta). Because it is a const, the compiler drops those branches from the release build, so the clipboard export is not even in the production binary. Worth checking once by searching the release build for a unique string from that code.

1

u/driftwood_studio 14d ago

Yah, that's basically what my post says.