name: flutter-expert description: Flutter and Dart expert. Load for any Flutter app work — widget trees, state management (Riverpod, BLoC, Provider, GetX), navigation (GoRouter, AutoRoute), platform channels, Firebase integration, performance tuning, and app store submission. Complements mobile-design (touch/UX) which should also be loaded for Flutter projects. Triggers on flutter, dart, riverpod, bloc, gorouter, pubspec, flutter pub, flutter build, flutter run. metadata: version: "1.0.0"
Flutter Expert — Dart & Flutter Development
Expert-level Flutter development covering architecture, state management, navigation, performance, platform integration, and release. Pairs with mobile-design for UX/touch concerns.
Philosophy
"Widget composition over inheritance. State at the right level. Platform feel without platform lock-in."
Flutter's power comes from its composable widget tree and Dart's strong typing. Abuse it and you get unmaintainable spaghetti. Use it well and you get apps that feel native on every platform.
Mandatory checkpoint (before any Flutter work)
🎯 FLUTTER CHECKPOINT:
Target: [ iOS / Android / Web / Desktop / All ]
State mgmt: [ Riverpod / BLoC / Provider / GetX / setState ]
Navigation: [ GoRouter / AutoRoute / Navigator 2.0 ]
Dart version: [ check pubspec.yaml ]
Files read: [ this SKILL.md + mobile-design/SKILL.md ]
If any item is unclear → ask the user before writing code.
Architecture principles
Widget tree discipline
| ❌ AVOID | ✅ DO | |
|---|
StatefulWidget for everything | Use StatelessWidget + state solution | |
| Business logic inside widgets | Extract to controllers/notifiers/blocs | |
| Deep nesting (>5 levels) | Extract into named widgets | |
setState in large trees | Scoped rebuilds with Riverpod/BLoC | |
BuildContext passed down | InheritedWidget / Provider / Riverpod | |
File structure (feature-first)
lib/
├── core/ # Shared utilities, theme, constants
│ ├── theme/
│ ├── utils/
│ └── errors/
├── features/ # Feature modules
│ ├── auth/
│ │ ├── data/ # Repos, data sources, DTOs
│ │ ├── domain/ # Entities, use cases
│ │ └── presentation/ # Screens, widgets, controllers
│ └── home/
├── shared/ # Shared widgets, components
└── main.dart
State management — Riverpod (preferred default)
Riverpod is the recommended choice for new Flutter projects. Use it unless the project already has BLoC/Provider established.
Provider types
| Need | Provider | |
|---|
| Simple value | Provider | |
| Async data (future) | FutureProvider | |
| Stream-based data | StreamProvider | |
| Mutable state + logic | NotifierProvider / AsyncNotifierProvider | |
| Global singleton (service) | Provider | |
Riverpod patterns
dart
// Notifier with async logic
@riverpod
class UserNotifier extends _$UserNotifier {
@override
Future<User> build() async {
return ref.watch(userRepositoryProvider).getUser();
}
Future<void> updateProfile(String name) async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(() =>
ref.read(userRepositoryProvider).update(name));
}
}
// Consuming in widget — scoped rebuild
class UserScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final user = ref.watch(userNotifierProvider);
return user.when(
data: (u) => UserView(user: u),
loading: () => const CircularProgressIndicator(),
error: (e, _) => ErrorWidget(error: e),
);
}
}
BLoC (when project already uses it)
dart
// Event → Bloc → State pattern
class AuthBloc extends Bloc<AuthEvent, AuthState> {
AuthBloc(this._repo) : super(AuthInitial()) {
on<LoginRequested>(_onLoginRequested);
}
Future<void> _onLoginRequested(
LoginRequested event, Emitter<AuthState> emit) async {
emit(AuthLoading());
try {
final user = await _repo.login(event.email, event.password);
emit(AuthSuccess(user));
} catch (e) {
emit(AuthFailure(e.toString()));
}
}
}
Navigation — GoRouter (preferred)
dart
final router = GoRouter(
initialLocation: '/',
redirect: (context, state) {
final isLoggedIn = context.read<AuthNotifier>().isLoggedIn;
if (!isLoggedIn && !state.matchedLocation.startsWith('/auth')) {
return '/auth/login';
}
return null;
},
routes: [
GoRoute(path: '/', builder: (ctx, _) => const HomeScreen()),
GoRoute(
path: '/user/:id',
builder: (ctx, state) => UserScreen(id: state.pathParameters['id']!),
),
ShellRoute(
builder: (ctx, state, child) => ScaffoldWithNavBar(child: child),
routes: [ /* tab routes */ ],
),
],
);
Performance — mandatory checklist
| Check | Pattern | |
|---|
| List rendering | ListView.builder with itemExtent when heights are fixed | |
| Large lists | flutter_lazy_load or pagination | |
| Image loading | cached_network_image — never raw Image.network | |
| Const widgets | Add const to every widget constructor possible | |
| Heavy builds | Use RepaintBoundary around animated sections | |
| Unnecessary rebuilds | Wrap specific watchers, not whole screens | |
| Memory leaks | Dispose controllers, subscriptions, animation controllers | |
dart
// Dispose correctly in StatefulWidget
@override
void dispose() {
_controller.dispose();
_subscription.cancel();
super.dispose();
}
Platform integration
Platform channels (native code bridge)
dart
// Dart side
const platform = MethodChannel('com.app/native');
Future<String> getNativeString() async {
try {
return await platform.invokeMethod<String>('getString') ?? '';
} on PlatformException catch (e) {
throw AppException('Native call failed: ${e.message}');
}
}
Conditional platform code
dart
import 'dart:io' show Platform;
Widget buildButton() {
if (Platform.isIOS) {
return CupertinoButton(onPressed: onTap, child: const Text('Go'));
}
return ElevatedButton(onPressed: onTap, child: const Text('Go'));
}
Firebase integration checklist
- [ ]
firebase_core initialized in main() before runApp - [ ]
google-services.json (Android) and GoogleService-Info.plist (iOS) in correct locations - [ ] Firestore security rules set (never open
allow read, write: if true) - [ ] Firebase Auth: use
authStateChanges() stream, not one-off calls - [ ] Crash reporting:
firebase_crashlytics initialized with FlutterError.onError
Testing patterns
dart
// Widget test
testWidgets('shows loading indicator', (tester) async {
await tester.pumpWidget(ProviderScope(
overrides: [userProvider.overrideWith(() => FakeUserNotifier())],
child: const MaterialApp(home: UserScreen()),
));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
});
// Unit test — notifier
test('login succeeds', () async {
final container = ProviderContainer(overrides: [
authRepositoryProvider.overrideWithValue(FakeAuthRepo()),
]);
final notifier = container.read(authNotifierProvider.notifier);
await notifier.login('a@b.com', 'pass');
expect(container.read(authNotifierProvider), isA<AsyncData<User>>());
});
Build & release commands
| Task | Command | |
|---|
| Run on device | flutter run | |
| Debug build (Android) | flutter build apk --debug | |
| Release build (Android) | flutter build apk --release | |
| App bundle (Play Store) | flutter build appbundle --release | |
| iOS release | flutter build ios --release | |
| Web | flutter build web --release | |
| Analyze code | flutter analyze | |
| Run tests | flutter test | |
| Check doctor | flutter doctor | |
Common errors and fixes
| Error | Cause | Fix | |
|---|
LateInitializationError | late var not initialized | Null-check or initialize in initState | |
setState called after dispose | Async callback after widget unmounted | Check mounted before setState | |
| Render overflow | Widget too large for parent | Wrap in SingleChildScrollView or Flexible | |
| Build context across async gaps | Outdated BuildContext | Store mounted check, or use ref (Riverpod) | |
| Gradle sync failure | SDK version mismatch | flutter clean && flutter pub get | |
| Pod install failure | CocoaPods out of date | pod repo update && pod install | |
Hard rules
- Never use `StatefulWidget` for business logic — extract to Notifier / BLoC / controller.
- Never call `setState` from outside the `State` class.
- Always dispose controllers — animation, text, page, scroll, stream subscriptions.
- Never block the main thread — heavy work goes in
Isolate or compute(). - Always handle loading + error states in async consumers (no naked
.data). - Never store sensitive data in `SharedPreferences` — use
flutter_secure_storage. - Run `flutter analyze` before every task complete — treat warnings as errors.
Quick reference
| Want to | Use | |
|---|
| State management | Riverpod (new) / BLoC (existing) | |
| Navigation | GoRouter | |
| HTTP | dio with interceptors, or http for simple | |
| Image cache | cached_network_image | |
| Secure storage | flutter_secure_storage | |
| Push notifications | firebase_messaging | |
| Local storage (non-sensitive) | shared_preferences / hive | |
| Large lists | ListView.builder + itemExtent | |
| Platform checks | Platform.isIOS / Platform.isAndroid | |
| Native bridge | MethodChannel | |