iTranslated by AI
[Flutter] Are you properly excluding debug screen source code from your release builds?
Whether it's Flutter or app development in general—or rather, frontend development as a whole—it is not uncommon to have a "debug screen" prepared.
Debug screens are convenient tools for efficient development and verification, allowing you to force-toggle feature flags to test unreleased features, fetch specific data to verify in the UI, manipulate cache contents, or check internal logs directly from the UI.
However, depending on the content, the source code for such debug screens and features can be analyzed by malicious third parties, potentially leading to serious security breaches. Therefore, I believe that at the very least, for features that do not need to be included in the release build, it is desirable to not only remove the entry point from the UI but to ensure they are not included in the binary at all.
Based on this philosophy, in this article, I would like to consider what kind of risks arise when debug screen and debug feature source code are included in a release binary, and how we can solve this problem.
Risks of Including Debug Screens in Release Builds
As I mentioned in my previous article, whether it is an Android APK file or an iOS IPA file, if you have a properly prepared device and follow the right procedures, it is possible to obtain, decompress, and inspect the binary.
At this point, since Dart code is compiled, you cannot read it as "source code," but that does not mean analysis is impossible. Obfuscation is merely "obfuscation," not "encryption," so it should be considered as "the difficulty increases, but in principle, it is analyzable with sufficient time and knowledge."
Furthermore, what is even more concerning is that string literals hardcoded in the source code can remain in the artifacts in their original form. Since strings appearing in a binary file can be easily extracted using commands like strings, if an experienced operator wants to extract string literals from the source code of an installed public app, it would take no more than a few minutes.
Now, with this premise, please check the source code of your debug screens.
Are URLs for testing environments, IDs for specific debug data, or explanations of unfinished features hardcoded in formats like Text(' ... ')? And are there any processes nearby that shouldn't be called by users?
Again, malicious third parties can read string literals included in the source code as they are, and obfuscated code can be analyzed over time. While the above pertains to static analysis of files, with more effort, dynamic analysis—such as actually running the app, dumping memory, or injecting arbitrary processes—is also possible.
In other words, it is no exaggeration to say that the source code of a debug screen is a treasure trove of content for attacks in the eyes of a malicious third party. Moreover, since these are completely unnecessary for actual users, leaving them in the binary means carrying unnecessary risks.
Dropping Debug Screen Source Code with Tree Shaking
So, I want to consider a way to "drop the debug screen source code in release builds."
One idea is to add a step in your CI to "delete .dart files related to debug screens in production builds." However, trying to mechanically delete source code to build may cause compile errors due to unexpected dependencies between files or classes. You might also forget to delete files when adding new debug features, or conversely, accidentally delete necessary files. In any case, it requires careful maintenance.
Therefore, I would like to explore how to utilize Dart's Tree shaking.
Tree shaking is a feature that automatically removes unused code that is not referenced at build time. Just like leaves falling when you shake a tree, it builds by dropping classes and other elements judged to be unnecessary from the reference graph.
In other words, the idea is that if you remove all references to the debug screen source code during a release build, the compiler will handle the exclusion automatically. Let's look at the specific method.
Separating main_dev.dart and main_prd.dart
The most straightforward method is to switch the main file specified by the -t option at runtime.

Instead of having a single main.dart, we split the file containing the main() function, which is called at app startup, into main_dev.dart and main_prd.dart. We then select the appropriate one depending on the build mode by specifying the -t option at runtime.
# Debug build
$ flutter build appbundle -t main_dev.dart
# Release build
$ flutter build appbundle -t main_prd.dart
All that's left is to make debug_page.dart a dependency only of main_dev.dart, ensuring that if main_prd.dart is used, there are no files left that depend on debug_page.dart.
Restricting Files that import debug_page.dart
Although we split main.dart into two, I think most Flutter app developers write various code in main.dart as well. Writing that code in both main_dev.dart and main_prd.dart would be very cumbersome. It seems better to leave most of the processing in main.dart and provide only the main() function in each file.
Since our requirement is simply that only main_dev.dart depends on debug_page.dart, we can implement it very easily like this:
// main.dart
void appMain({Widget? debugPage}) {
// main process
runApp(MyApp(debugPage: debugPage)),
}
class MyApp extends StatefulWidget {
// Implementation of regular MyApp
}
First, rename the original main() function in main.dart. I used appMain() here. It accepts an optional Widget? debugPage argument, but everything else remains the same.
Next, define the main() function in both main_dev.dart and main_prd.dart and call this appMain().
import 'package:my_app/debug/debug_page.dart'; // Dependency on debug_page.dart
import 'package:my_app/main.dart';
// Pass the debug screen when calling main.dart
void main() => appMain(debugPage: const DebugPage());
// The release build does not depend on debug_page.dart
import 'package:debug_page_practice/main.dart';
// Just call main.dart
void main() => appMain();
In the debug build, we pass DebugPage(), and in the release build, we pass nothing. By doing this, main_prd.dart no longer needs to depend on debug_page.dart.
Once the dependency on debug_page.dart is gone, the Tree shaking feature will exclude debug_page.dart before compilation during the build process, ensuring it is not included in the resulting APK or IPA—that is the strategy.

Finally, let's create a mechanism to navigate to the debug screen using the debugPage received in appMain().
Implementing the Mechanism to Navigate to DebugPage
As you can see from the flow so far, if "arbitrary screens" were to write DebugPage() directly as they pleased, it would defeat the purpose of organizing dependencies to exclude DebugPage from the release build. Therefore, we add a "method to open the debug screen" that can be called universally to main.dart.
There are various ways to do this, but since we need to navigate using widget.debugPage from _MainAppState, I plan to implement a custom .of(context) method in MainApp to find the _MainAppState object from the widget tree and implement the specific navigation logic within _MainAppState.[1]
class MainApp extends StatefulWidget {
const MainApp({super.key, this.debugPage});
final Widget? debugPage;
/// Function to find [_MainAppState]
static _MainAppState of(BuildContext context) {
return context.findAncestorStateOfType<_MainAppState>()!;
}
@override
State<MainApp> createState() => _MainAppState();
}
With this, you can retrieve the _MainAppState object from anywhere in the app by calling MainApp.of(context).
Let's add the "specific logic to navigate to widget.debugPage" to _MainAppState as follows.
class _MainAppState extends State<MainApp> {
/// [GlobalKey] to allow navigation from arbitrary processes
final _navigatorKey = GlobalKey<NavigatorState>();
/// Opens the debug page. Does nothing if [widget.debugPage] is null.
Future<void> openDebugPage() async {
if (widget.debugPage == null) {
return;
}
// Execute navigation
await _navigatorKey.currentState?.push(
MaterialPageRoute<void>(builder: (_) => widget.debugPage!),
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Debug Page Practice',
navigatorKey: _navigatorKey, // Set the GlobalKey used for navigation
home: const HomePage(),
);
}
}
By doing this, any part of the code that wants to navigate to the debug screen can simply call MainApp.of(context).openDebugPage(). And since widget.debugPage is null in release builds, nothing will happen even if it is called.
Confirming that the Debug Screen Source Code was Dropped
Finally, let's verify that debug_page.dart is indeed not included in the binary.
While you could generate an APK, unzip it, and search for the DebugPage symbol in the contents, there is a slightly easier method. That is the --analyze-size option.
By adding the --analyze-size option to flutter build apk, a JSON file is generated for analyzing the detailed file size information of the produced binary. Since this file also includes file names and class names included in the build, if strings like debug_page.dart or DebugPage are gone from it, it serves as proof that the debug screen source code was indeed excluded by Tree shaking.
Let's actually try it.
$ flutter build apk --release -t lib/main_prd.dart --analyze-size --target-platform android-arm64
When using --analyze-size, you must narrow down the build target to a single platform. I have specified android-arm64 here, but since all we need to verify is "whether the debug screen code is included," anything works.
$ flutter build apk --release -t lib/main_prd.dart --analyze-size --target-platform android-arm64
Font asset "MaterialIcons-Regular.otf" was tree-shaken, reducing it from 1645184 to 1484 bytes (99.9% reduction). Tree-shaking can be disabled by providing the --no-tree-shake-icons flag when building your app.
Running Gradle task 'assembleRelease'... 9.7s
✓ Built build/app/outputs/flutter-apk/app-release.apk (14.6MB)
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
app-release.apk (total compressed) 14 MB
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
assets/
flutter_assets 109 KB
classes.dex 211 KB
lib/
arm64-v8a 14 MB
Dart AOT symbols accounted decompressed size 3 MB
package:flutter 2 MB
dart:core 223 KB
... (omitted) ...
dart:nativewrappers 169 B
dart:vmservice_io 107 B
kotlin/
collections 2 KB
concurrent 1 KB
kotlin.kotlin_builtins 5 KB
ranges 1 KB
reflect 1 KB
AndroidManifest.xml 2 KB
res/
o-.png 1 KB
resources.arsc 10 KB
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
A summary of your APK analysis can be found at: /Users/chooyan/.flutter-devtools/apk-code-size-analysis_01.json
To analyze your app size in Dart DevTools, run the following command:
dart devtools --appSizeBase=/Users/chooyan/.flutter-devtools/apk-code-size-analysis_01.json
Then, simply open apk-code-size-analysis_01.json at the indicated path and search for strings like DebugPage or debug_page.dart to verify.
Although I haven't tested it myself, since it's just finding specific strings in files generated by the build, the same check could be performed in CI. It would be wise to add this check to CI so that you can detect if Tree shaking stops working as you expand the debug screen features.
With this, we have achieved "excluding debug screen source code from the release build."
Conclusion
When a malicious third party attempts to attack specific software, the more "information" they have, the easier it is for the attack to succeed.
Since the code for debug screens and features often contains a lot of information that is easy to use as a foothold, and because they are completely unnecessary for regular users, I think it is best to build your implementation such that it includes "removing them during release builds" from the start.
Furthermore, to ensure this mechanism doesn't become a mere formality or get disabled, it is a good idea to consider techniques such as using lint to block dependencies on the debug/ folder or using AI review rules to detect direct navigation to DebugPage.
As debug screens are frequently prepared regardless of whether it's a corporate or personal project, I believe the methods introduced in this article are worth considering as countermeasures against attacks targeting those areas.
-
For information on what
findAncestorStateOfType()does and why it is used, please read Everything I can write about BuildContext alongside this article. ↩︎
Discussion
dart-defineやdart-define-from-fileから実行時定数をセットすることで、ビルドに応じてデバッグ用のコードを到達不能にするのはどうでしょうか。例えばのように定義すれば
flutter build apk --dart-define=ENABLE_DEBUG=trueの時だけ参照されるようになるはずです。フラグ単体で処理するのが厄介であれば、ちょっとpragmaの動作に依存してしまうのですが、のようにすると、任意の環境設定に応じて対応できるかなと。ただ、inline化によるconst定数の伝播になるので、前者より後者は不確実なハズです!
ありがとうございます!コンパイル時に参照を無くす(それによってバイナリにコードが含まれなくなる)のが
--dart-defineによる分岐で達成できるのかがまだよく分かっておらず、そのあたりの仕組みの調査とサンプル作って実験してみようと思います。dartの
constがコンパイル時に評価されることから、コンパイル時に到達不可能と判断されたコードはtree-shakingの削除対象になる…と自分は理解しています。ただ、これはconst以外にもpragmaの指定により判定を行わせられるように発展してきており、ドキュメントが追いついていない状態かもしれません。。最近 (?) 追加されたドキュメントがこれです。
理解している自信がないのですが、なんとなく雰囲気で分かった気分になったissueとかです。
おお、詳しく資料までありがとうございます!あとは記事に書いた方法で実際に手元で試せば見えてきそうです。
調べて考えてみたところトリッキーな話だったので、記事にしました!
ざっと読ませていただきました!pragma まで活用して工夫しているプロジェクトは自分の経験では見たことなかったですねー、、!せいぜいパッケージのドキュメントに
@pragma(xxx)をつけてね、と書いてあったらつける、くらいの認識でした。また時間確保してじっくり読ませていただきます。この記事からもリンク追加します!