Const Objects and Compile-Time Constants
Const Objects and Compile-Time Constants
About
- Compile-Time Constants are values determined during compilation.
- Created using
const
keyword for immutable values. - More efficient than regular objects (single instance in memory).
- Used extensively in Flutter widget trees.
Main Topics
-
Basic Const Usage
- Definition: Creating simple constants.
- Example:
const defaultPadding = 8.0; const appName = 'MyApp';
-
Const Constructors
- Definition: Creating immutable classes.
- Example:
class Point { final double x, y; const Point(this.x, this.y); }
-
Const Collections
- Definition: Immutable lists/maps/sets.
- Example:
const colors = ['red', 'green', 'blue']; const config = {'debug': false, 'retries': 3};
-
Performance Benefits
- Definition: Memory and speed advantages.
- Example:
// One instance shared everywhere: const emptyList = const [];
-
When to Use Const
- Definition: Ideal use cases.
- Example:
// Good for: // - Widget constructors // - Configuration values // - Default parameters
How to Use
- Widgets: Always use const for stateless widgets
- Collections: Use for immutable data
- Constructors: Mark classes with const when possible
- Parameters: Use for default values
How It Works
- Compilation: Values evaluated at compile time
- Canonicalization: Single instance reused
- Tree Shaking: Unused constants removed
- Embedding: Stored in special constant pool
Example Widget Optimization:
@override
Widget build() {
return const MyWidget( // Saves rebuilds
child: const Text('Hello'),
);
}
Conclusion
Const objects and compile-time constants are powerful Dart features that improve application performance through memory sharing and immutable data. Their proper use significantly reduces widget rebuilds in Flutter and optimizes memory usage across the entire application.