Trimming the Flutter Tree

Tree Shaking and Compilation Constants

By Liber Da Silva

Agenda

  • Understanding Tree Shaking
  • Compilation Constants vs Runtime Constants
  • Optimizing with Compilation Constants
  • Using dart-define
  • Practical Examples

Tree Shaking in Flutter

Removing unused code from the final application

How Tree Shaking Works

  1. Static code analysis
  2. Building dependency tree
  3. Identifying dead code
  4. Removal during compilation

Importance

  • Reduces app size
  • Improves performance
  • Optimizes for multiple configs
  • Cons: We don't have reflection

Compilation Constants vs Runtime Constants

Compilation Constants

  • Resolved at compile-time
  • Allow aggressive optimizations
  • No runtime memory overhead

							const color = Color(0xFFC4C4C4);
							const apiKey = String.fromEnvironment('API_KEY');
						

Inlining and Compile-Time Evaluation


						const int value1 = 10;
						const int value2 = 20;
						const int sumValues = value1 + value2; // Calculated at compile-time
						

Runtime Constants

  • Resolved at runtime
  • More flexible, but limit optimizations
  • Occupy memory during execution

Example

  • Instance reuse
  • Improved rebuild performance

		class MyWidget extends StatelessWidget {
			const MyWidget({Key? key, required this.title}) : super(key: key);
		
			final String title;
		
			@override
			Widget build(BuildContext context) {
				return Text(title);
			}
		}
								

Optimizing with Compilation Constants

Dead Code Elimination


const bool isDebug = bool.fromEnvironment('DEBUG');

void main() {
  if (isDebug) {
    // This code will be removed in production
    setupDebugTools();
  }
}
						

Using dart-define

Command Line Usage


				flutter run --dart-define=API_KEY=my_api_key
						

In Code


				const apiKey = String.fromEnvironment('API_KEY');
						

Loading from File

Create a .env (or .json) file:


				API_KEY=my_api_key
				DEBUG_MODE=true
						

Run with:


				flutter run --dart-define-from-file=.env
						

Access in code:


				const apiKey = String.fromEnvironment('API_KEY');
				const debugMode = bool.fromEnvironment('DEBUG_MODE');
						

Practical Examples

Let's code!