--- description: Flutter UI patterns, widget best practices, and performance optimization. Apply to all presentation-layer Dart files. globs: "lib/**/{widgets,pages,screens,components}/**/*.dart" --- # Flutter UI & Performance Rules ## Widget Best Practices - Create small, private widget classes instead of methods like `Widget _buildXxx()`. - Use const constructors for all immutable widgets. - Implement proper widget keys for lists and conditional widgets. - Keep widget tree flat — avoid nesting deeper than necessary. - Use composition: combine small widgets into complex ones. ## Performance Optimization - Use ListView.builder / GridView.builder for long scrollable lists. - Use const wherever possible to skip unnecessary rebuilds. - Avoid expensive operations (network calls, parsing) in build(). - Use compute() to run heavy work in a background isolate. - Use RepaintBoundary to isolate expensive paint operations. - Cache images: AssetImage for local, cached_network_image for remote. - Profile regularly with Flutter DevTools; target 60fps. ## Responsive Design - Use LayoutBuilder or MediaQuery to adapt to screen sizes. - Use Expanded/Flexible in Row/Column to prevent overflow. - Use Wrap for content that may overflow horizontally. - Use FittedBox to scale a child within its parent. ## Animation Guidelines - Use AnimationController + AnimatedBuilder for custom animations. - Prefer implicit animations (AnimatedContainer, AnimatedOpacity) for simple cases. - Use physics-based animations (SpringSimulation) for natural feel. - Always dispose AnimationControllers in dispose(). ## Theming in Widgets - Access colors via Theme.of(context).colorScheme. - Access text styles via Theme.of(context).textTheme. - Never hardcode colors or font sizes — always reference theme. - Use Theme.of(context).extension() for custom design tokens. ## Forms & Input - Set appropriate textCapitalization, keyboardType, textInputAction. - Always include errorBuilder when using Image.network. - Implement RefreshIndicator for pull-to-refresh. - Use Form + GlobalKey for validation. ## Accessibility - Use Semantics widget for all interactive elements. - Ensure touch targets ≥ 48x48 dp. - Test with screen readers (TalkBack / VoiceOver). - Support dynamic type scaling.