Flutter/Dart Best Practices
Widget Composition
- Build UI from small, composable widgets; each widget should do one thing well
- Use
constconstructors wherever possible -- enables compile-time optimizations and faster rebuilds - Prefer stateless widgets; only use
StatefulWidgetwhen the widget manages mutable state - Apply the
Widgetcomposition pattern: container widgets handle state, leaf widgets are purely presentational - Extract repeated UI patterns into reusable widgets in a
widgets/orcomponents/directory
State Management
- Use Riverpod as the primary state management solution:
Providerfor dependencies,Notifierfor state - Define providers at the top level; use
ref.watchin widgets andref.readin callbacks - Use
AsyncValuefor loading/error/data state handling:when(loading:, error:, data:) - For BLoC pattern: define events, states, and blocs; use
BlocBuilder,BlocListener,BlocConsumerin UI - Keep state immutable; create new state instances on change rather than mutating in place
Platform Channels
- Use
MethodChannelfor calling platform-specific APIs from Dart to native (Kotlin/Swift) - Use
EventChannelfor streaming platform events to Dart: sensor data, connectivity changes - Register channels in
MainActivity(Android) andAppDelegate(iOS) with matching channel names - Use
Pigeonfor type-safe platform channel code generation instead of manual serialization - Keep platform-specific code minimal; push as much logic as possible into the shared Dart layer
Responsive Layout
- Use
MediaQueryfor screen-size-dependent layouts;LayoutBuilderfor parent-constrained layouts - Apply
FlexibleandExpandedwithinRow/Columnfor proportional sizing - Use
SingleChildScrollViewwithConstrainedBoxfor scrollable forms; avoid unbounded heights - Define breakpoints in a constants file: mobile (<600), tablet (600-1200), desktop (>1200)
- Test layouts with
DevicePreviewpackage across screen sizes before physical device testing
Testing
- Write widget tests with
testWidgets: pump the widget, find elements, verify behavior - Use
mockitoormocktailfor mocking dependencies in unit tests - Create golden tests for critical UI components:
matchesGoldenFile('goldens/widget.png') - Run
flutter test --coveragein CI; enforce minimum coverage thresholds for core logic - Integration tests in
integration_test/useIntegrationTestWidgetsFlutterBindingfor device testing
Source: calcosmic/Aether — distributed by TomeVault.