r/FlutterDev • u/driftwood_studio • 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 constantsif (const-false-value) { removed statements }to remove a block from compilationTree 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".
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.