Introduction
In Phase 0, we covered the foundations: Dart's async model, null safety, the widget tree, layout constraints, and the tooling. Phase 1 is where those foundations become applications. The questions change from "How do I draw this screen?" to:
- How do users move between screens, and how does data travel with them?
- Who owns the state, and what happens when it changes?
- How do I know my code works, and that it works for everyone?
- How do I build UI that is consistent, reusable, and fast?
Phase 1 has four pillars:
- Navigation, data passing, and screen-state preservation
- State management: ownership, immutable state, asynchronous state, and lifecycle
- Unit testing, accessibility, localization, and keyboard handling
- Widget composition, keys, scrolling, themes, and reusable components
Throughout this post I use a small banking-style app (an accounts list and a transfer form) as the running example. It is simple enough to follow and realistic enough to show why each topic matters.
Prerequisites: Basic Dart (null safety, async/await) and the widget fundamentals from Phase 0.
Part 1: Navigation, Data Passing, and Screen-State Preservation
1.1 How navigation works in Flutter
Flutter keeps a stack of pages. Pushing adds a page on top, and popping removes it. There are two APIs:
- Navigator 1.0 (imperative):
Navigator.push,Navigator.pop. Simple and ideal for learning. - Router / Navigator 2.0 (declarative): The app state determines the page stack. It supports deep links, the web URL bar, and redirect guards. In practice, most teams use the
go_routerpackage, which wraps it.
Learn the basics first, then move to go_router for anything beyond a toy app.
1.2 Navigator 1.0: push and pop
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const AccountDetailScreen()),
);
// Go back
Navigator.of(context).pop();
Passing data forward means passing it through the constructor. This is type-safe and the simplest approach.
class AccountDetailScreen extends StatelessWidget {
const AccountDetailScreen({super.key, required this.account});
final Account account;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(account.name)),
body: Center(child: Text('Balance: ${account.balance}')),
);
}
}
// Usage
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => AccountDetailScreen(account: selectedAccount),
),
);
Returning data backward: push returns a Future that completes when the page is popped.
final bool? confirmed = await Navigator.of(context).push<bool>(
MaterialPageRoute(builder: (_) => const ConfirmTransferScreen()),
);
if (!context.mounted) return;
if (confirmed == true) {
// proceed with the transfer
}
// Inside ConfirmTransferScreen
Navigator.of(context).pop(true);
Tip: After every
await, checkif (!context.mounted) return;before usingcontext. The widget may have been removed from the tree while you were waiting.
Named routes (Navigator.pushNamed) exist, but they are limited for typed arguments and deep links. Flutter's own documentation recommends a router package such as go_router for most apps.
1.3 Declarative navigation with go_router
Add the package:
# pubspec.yaml
dependencies:
go_router: ^<latest version from pub.dev>
Define your routes in one place:
1final router = GoRouter(
2 initialLocation: '/accounts',
3 routes: [
4 GoRoute(
5 path: '/accounts',
6 builder: (context, state) => const AccountsScreen(),
7 routes: [
8 GoRoute(
9 path: ':id', // /accounts/42
10 builder: (context, state) {
11 final id = state.pathParameters['id']!;
12 return AccountDetailScreen(accountId: id);
13 },
14 ),
15 ],
16 ),
17 GoRoute(
18 path: '/transfer',
19 builder: (context, state) {
20 final from = state.extra as Account?; // complex object
21 return TransferScreen(source: from);
22 },
23 ),
24 ],
25);
26
27// main.dart
28void main() => runApp(const MyApp());
29
30class MyApp extends StatelessWidget {
31 const MyApp({super.key});
32
33 @override
34 Widget build(BuildContext context) {
35 return MaterialApp.router(routerConfig: router);
36 }
37}
Navigating:
context.go('/accounts/42'); // replaces the stack
context.push('/transfer', extra: selectedAccount); // adds to the stack
final ok = await context.push<bool>('/confirm'); // get a result
context.pop(true); // return a result
go vs push: go navigates to a location and rebuilds the stack to match it. push adds one page on top of the current stack. Use go for moving between top-level destinations and push for temporary flows such as "confirm" or "pick a contact."
Query parameters for optional filters:
context.go('/accounts?type=savings');
// In the route builder
final type = state.uri.queryParameters['type']; // 'savings'
1.4 Redirects and guards
Redirects let you protect routes, for example sending logged-out users to the login screen:
final router = GoRouter(
refreshListenable: authNotifier, // re-evaluates when auth changes
redirect: (context, state) {
final loggedIn = authNotifier.isLoggedIn;
final goingToLogin = state.matchedLocation == '/login';
if (!loggedIn && !goingToLogin) return '/login';
if (loggedIn && goingToLogin) return '/accounts';
return null; // no redirect
},
routes: [ /* ... */ ],
);
This pattern becomes essential in Phase 2 and 3 when you handle authentication and session flows.
1.5 Which way should data travel?
- Constructor argument: Best for direct widget-to-widget passing. Watch out for tight coupling in large apps.
- Path parameter (
:id): Best for identifiers and deep-linkable data. Values are strings, so parse and validate them. - Query parameter (
?tab=2): Best for optional filters and flags. Also strings. extra: Best for complex objects in simple flows. It is lost on web refresh and does not survive deep links.- Shared state (provider): Best for data many screens need. It requires a clear owner.
Best practice: Pass an ID, not the whole object, and let the destination screen load what it needs from a repository or state layer. This makes deep links work and avoids showing stale data.
1.6 Screen-state preservation
Users expect that switching tabs does not reset their scroll position or half-filled form. By default, Flutter disposes a page's state when it leaves the tree. There are several ways to preserve state.
a) IndexedStack keeps every child alive.
IndexedStack(
index: currentIndex,
children: const [HomeTab(), AccountsTab(), ProfileTab()],
)
It is the simplest option. The trade-off is that every tab is built up front and stays in memory.
b) StatefulShellRoute in go_router gives each tab its own navigation stack.
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) =>
ScaffoldWithNavBar(navigationShell: navigationShell),
branches: [
StatefulShellBranch(routes: [
GoRoute(path: '/home', builder: (_, __) => const HomeTab()),
]),
StatefulShellBranch(routes: [
GoRoute(path: '/accounts', builder: (_, __) => const AccountsTab()),
]),
],
)
Each tab remembers where the user was. If they drill into /accounts/42 and switch to Home and back, they return to account 42. This is the pattern used by most banking and social apps.
Wire the bottom navigation bar to the shell:
1class ScaffoldWithNavBar extends StatelessWidget {
2 const ScaffoldWithNavBar({super.key, required this.navigationShell});
3
4 final StatefulNavigationShell navigationShell;
5
6 @override
7 Widget build(BuildContext context) {
8 return Scaffold(
9 body: navigationShell,
10 bottomNavigationBar: NavigationBar(
11 selectedIndex: navigationShell.currentIndex,
12 onDestinationSelected: (index) => navigationShell.goBranch(
13 index,
14 // Tapping the active tab returns to its root
15 initialLocation: index == navigationShell.currentIndex,
16 ),
17 destinations: const [
18 NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
19 NavigationDestination(icon: Icon(Icons.account_balance), label: 'Accounts'),
20 ],
21 ),
22 );
23 }
24}
c) AutomaticKeepAliveClientMixin keeps one item alive inside a scrollable, TabBarView, or PageView.
class _AccountsTabState extends State<AccountsTab>
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context); // required
return const AccountsList();
}
}
d) PageStorageKey preserves scroll position.
ListView.builder(
key: const PageStorageKey<String>('accounts-list'),
itemCount: accounts.length,
itemBuilder: (context, i) => AccountTile(account: accounts[i]),
)
e) Hoist the state. If form data lives in a state-management layer rather than inside the widget, it survives the widget being disposed. This is often the cleanest solution and leads directly into Part 2.
f) State restoration (for process death). When Android kills your app in the background, the OS can restore it using RestorationMixin and RestorableProperty types such as RestorableTextEditingController. Use it for small, UI-level state like scroll offsets and in-progress text, not for business data.
1.7 Intercepting back navigation
Warn users before they lose unsaved work with PopScope:
1PopScope(
2 canPop: !hasUnsavedChanges,
3 onPopInvokedWithResult: (didPop, result) async {
4 if (didPop) return;
5 final discard = await showDialog<bool>(
6 context: context,
7 builder: (_) => AlertDialog(
8 title: const Text('Discard transfer?'),
9 content: const Text('Your changes will be lost.'),
10 actions: [
11 TextButton(
12 onPressed: () => Navigator.pop(context, false),
13 child: const Text('Keep editing'),
14 ),
15 TextButton(
16 onPressed: () => Navigator.pop(context, true),
17 child: const Text('Discard'),
18 ),
19 ],
20 ),
21 );
22 if (discard == true && context.mounted) Navigator.pop(context);
23 },
24 child: const TransferForm(),
25)
1.8 Common navigation mistakes
- Using
contextafter anawaitwithout checkingmounted. - Passing large objects through
extraand then wondering why deep links crash. - Using
gowhen you meantpush, which silently removes the previous screens. - Rebuilding the
GoRouterinsidebuild(). Create it once and keep it stable. - Forgetting that
state.pathParametersvalues are always strings.
Part 2: State Management
2.1 What is "state"?
State is any data that can change over time and affects what the UI shows. Flutter's central rule is:
UI = f(state)
You do not tell widgets to change. You change the state, and the framework rebuilds the UI to match. Good state management answers four questions:
- Where does this state live? (ownership)
- Who is allowed to change it? (encapsulation)
- How do widgets find out it changed? (notification)
- When is it created and destroyed? (lifecycle)
2.2 Ephemeral state vs app state
- Ephemeral (local) state belongs to a single widget and nobody else cares about it: the selected tab, an animation progress, whether a password is obscured. Use
StatefulWidgetandsetState. - App (shared) state is needed in multiple places or must outlive a screen: the logged-in user, the accounts list, a shopping cart. Use a state-management solution.
There is no hard rule, but a good question is: "Would another screen, a test, or a refresh need this?" If yes, it is app state.
1class ObscuredPasswordField extends StatefulWidget {
2 const ObscuredPasswordField({super.key});
3
4 @override
5 State<ObscuredPasswordField> createState() => _ObscuredPasswordFieldState();
6}
7
8class _ObscuredPasswordFieldState extends State<ObscuredPasswordField> {
9 bool _obscure = true; // ephemeral: nobody else cares
10
11 @override
12 Widget build(BuildContext context) {
13 return TextField(
14 obscureText: _obscure,
15 decoration: InputDecoration(
16 labelText: 'Password',
17 suffixIcon: IconButton(
18 icon: Icon(_obscure ? Icons.visibility : Icons.visibility_off),
19 onPressed: () => setState(() => _obscure = !_obscure),
20 ),
21 ),
22 );
23 }
24}
2.3 State ownership: lift state up
When two widgets need the same data, move the state to their closest common ancestor and pass data down while events travel up.
1// Parent owns the state
2class TransferPage extends StatefulWidget {
3 const TransferPage({super.key});
4
5 @override
6 State<TransferPage> createState() => _TransferPageState();
7}
8
9class _TransferPageState extends State<TransferPage> {
10 Account? _source;
11
12 @override
13 Widget build(BuildContext context) {
14 return Column(
15 children: [
16 AccountPicker(
17 selected: _source, // data flows down
18 onChanged: (a) => setState(() => _source = a), // events flow up
19 ),
20 BalancePreview(account: _source),
21 ],
22 );
23 }
24}
This works, but passing data through many layers ("prop drilling") gets painful. That is where a dedicated state-management solution comes in.
A single source of truth: each piece of state should have exactly one owner. If two widgets keep their own copy of the account balance, they will eventually disagree.
2.4 Immutable state
Prefer immutable state objects. Instead of mutating a field, create a new object with the change. Flutter and most state libraries detect a change by comparing references or equality, so mutation can leave the UI stale.
// BAD: mutating in place
state.accounts.add(newAccount); // listeners may never notice
// GOOD: replace with a new value
state = state.copyWith(accounts: [...state.accounts, newAccount]);
A simple immutable model:
1@immutable
2class TransferState {
3 const TransferState({
4 this.source,
5 this.destination,
6 this.amount = 0,
7 this.isSubmitting = false,
8 this.errorMessage,
9 });
10
11 final Account? source;
12 final Account? destination;
13 final double amount;
14 final bool isSubmitting;
15 final String? errorMessage;
16
17 TransferState copyWith({
18 Account? source,
19 Account? destination,
20 double? amount,
21 bool? isSubmitting,
22 String? errorMessage,
23 }) {
24 return TransferState(
25 source: source ?? this.source,
26 destination: destination ?? this.destination,
27 amount: amount ?? this.amount,
28 isSubmitting: isSubmitting ?? this.isSubmitting,
29 errorMessage: errorMessage, // intentionally not "??" so it can be cleared
30 );
31 }
32
33 @override
34 bool operator ==(Object other) =>
35 other is TransferState &&
36 other.source == source &&
37 other.destination == destination &&
38 other.amount == amount &&
39 other.isSubmitting == isSubmitting &&
40 other.errorMessage == errorMessage;
41
42 @override
43 int get hashCode =>
44 Object.hash(source, destination, amount, isSubmitting, errorMessage);
45}
Writing copyWith, ==, and hashCode by hand is tedious. Packages such as freezed or equatable generate or simplify them. Dart 3 sealed classes are also excellent for modeling mutually exclusive states (shown below).
Why immutability matters:
- Predictable: state only changes through explicit transitions.
- Easy to test: compare before and after.
- Easy to debug: you can log every state change.
- Safe: no widget can secretly modify data another widget is displaying.
2.5 Options for state management
Flutter does not force one approach. The common choices:
ChangeNotifier+Provider: Simple, built on Flutter primitives. Good for small to mid-size apps and for learning.- Riverpod: Compile-safe, testable, and not dependent on
BuildContext. Popular for scalable apps. - BLoC / Cubit: Strict event-to-state flow with streams. Popular in enterprise and banking apps because of its predictability.
ValueNotifier/ValueListenableBuilder: Lightweight for a single value.
The principles in this post apply to all of them. Follow your team's convention and learn the principles deeply; the syntax is the easy part. The examples below use ChangeNotifier and Riverpod because they illustrate the ideas with the least ceremony.
2.6 Example: ChangeNotifier with Provider
class AccountsNotifier extends ChangeNotifier {
AccountsNotifier(this._repository);
final AccountRepository _repository;
List<Account> _accounts = const [];
List<Account> get accounts => List.unmodifiable(_accounts);
Future<void> load() async {
_accounts = await _repository.fetchAccounts();
notifyListeners();
}
}
1void main() {
2 runApp(
3 ChangeNotifierProvider(
4 create: (_) => AccountsNotifier(AccountRepository())..load(),
5 child: const MyApp(),
6 ),
7 );
8}
9
10// Reading in a widget
11class AccountsList extends StatelessWidget {
12 const AccountsList({super.key});
13
14 @override
15 Widget build(BuildContext context) {
16 final accounts = context.watch<AccountsNotifier>().accounts; // rebuilds on change
17 return ListView(
18 children: [for (final a in accounts) AccountTile(account: a)],
19 );
20 }
21}
22
23// Calling an action without subscribing to rebuilds
24onPressed: () => context.read<AccountsNotifier>().load(),
watch vs read: watch subscribes the widget to changes, so use it in build. read gets the object once without subscribing, so use it in callbacks. Never use read to display data that changes, and never use watch inside onPressed.
Rebuild optimization: Use context.select to rebuild only when one specific value changes.
final count = context.select<AccountsNotifier, int>((n) => n.accounts.length);
2.7 Asynchronous state: loading, data, error
Almost all real screens fetch data, so every async screen has at least these states:
- Loading
- Success (data)
- Empty (success, but nothing to show)
- Error (with a way to retry)
Model them explicitly rather than with scattered booleans like isLoading, hasError, and data, which can contradict each other (for example isLoading == true and hasError == true).
A sealed class makes impossible states unrepresentable:
sealed class AccountsState {
const AccountsState();
}
class AccountsLoading extends AccountsState {
const AccountsLoading();
}
class AccountsLoaded extends AccountsState {
const AccountsLoaded(this.accounts);
final List<Account> accounts;
}
class AccountsFailure extends AccountsState {
const AccountsFailure(this.message);
final String message;
}
The UI uses an exhaustive switch. The compiler warns you if you forget a case:
Widget build(BuildContext context) {
final state = context.watch<AccountsNotifier>().state;
return switch (state) {
AccountsLoading() => const Center(child: CircularProgressIndicator()),
AccountsFailure(:final message) => ErrorView(
message: message,
onRetry: () => context.read<AccountsNotifier>().load(),
),
AccountsLoaded(:final accounts) when accounts.isEmpty =>
const EmptyView(message: 'No accounts yet'),
AccountsLoaded(:final accounts) => AccountsList(accounts: accounts),
};
}
The notifier drives the transitions and handles errors:
1class AccountsNotifier extends ChangeNotifier {
2 AccountsNotifier(this._repository);
3
4 final AccountRepository _repository;
5
6 AccountsState _state = const AccountsLoading();
7 AccountsState get state => _state;
8
9 Future<void> load() async {
10 _state = const AccountsLoading();
11 notifyListeners();
12
13 try {
14 final accounts = await _repository.fetchAccounts();
15 _state = AccountsLoaded(accounts);
16 } on TimeoutException {
17 _state = const AccountsFailure('The request timed out. Please try again.');
18 } catch (e) {
19 _state = const AccountsFailure('Something went wrong.');
20 }
21 notifyListeners();
22 }
23}
2.8 Asynchronous state with Riverpod
Riverpod models this pattern directly with AsyncValue, which has loading, data, and error built in:
@riverpod
class Accounts extends _$Accounts {
@override
Future<List<Account>> build() {
return ref.watch(accountRepositoryProvider).fetchAccounts();
}
Future<void> refresh() async {
state = const AsyncLoading();
state = await AsyncValue.guard(
() => ref.read(accountRepositoryProvider).fetchAccounts(),
);
}
}
class AccountsScreen extends ConsumerWidget {
const AccountsScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final accounts = ref.watch(accountsProvider);
return accounts.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => ErrorView(
message: 'Could not load accounts',
onRetry: () => ref.invalidate(accountsProvider),
),
data: (list) => list.isEmpty
? const EmptyView(message: 'No accounts yet')
: AccountsList(accounts: list),
);
}
}
The @riverpod annotation uses code generation (riverpod_generator plus build_runner). You can also write providers by hand without generation.
Common async pitfalls:
- Race conditions: A user types fast and an older, slower response overwrites a newer one. Cancel or ignore stale requests.
- Updating after dispose: Check
mountedin widgets, and guard notifiers against callingnotifyListeners()afterdispose(). - Double submit: Disable the button while
isSubmittingis true. - Swallowed errors: An empty
catchhides bugs. Always translate failures into user-facing state. - Forgetting the empty state: An empty list is a legitimate result, not an error.
2.9 Lifecycle management
State objects have a lifecycle, and resources must be released.
StatefulWidget lifecycle:
1class _TransferFormState extends State<TransferForm> {
2 late final TextEditingController _amountController;
3 late final FocusNode _amountFocus;
4 StreamSubscription<double>? _rateSub;
5
6 @override
7 void initState() {
8 super.initState(); // called once
9 _amountController = TextEditingController();
10 _amountFocus = FocusNode();
11 _rateSub = rateStream.listen(_onRate);
12 }
13
14 @override
15 void didUpdateWidget(covariant TransferForm oldWidget) {
16 super.didUpdateWidget(oldWidget); // parent rebuilt with new config
17 }
18
19 @override
20 void dispose() {
21 _rateSub?.cancel();
22 _amountController.dispose();
23 _amountFocus.dispose();
24 super.dispose(); // called once when removed
25 }
26
27 @override
28 Widget build(BuildContext context) => const SizedBox(); // may run many times
29}
Key rules:
- Create controllers, focus nodes, animation controllers, and subscriptions in
initState, and always release them indispose. buildcan run many times. Keep it pure and fast, with no network calls and no side effects.didChangeDependenciesruns when an inherited widget the state depends on changes (for exampleThemeorLocalizations).
Provider/notifier lifecycle:
- With
Provider, notifiers created viacreate:are disposed automatically when the provider leaves the tree. - With Riverpod,
autoDisposeproviders clean up when no one is listening. Useref.onDisposeto cancel timers or streams. - Decide scope deliberately: app-wide state (auth, settings) at the root, and feature state scoped to the feature's route so it is released when the user leaves.
App lifecycle (foreground, background) can be observed with WidgetsBindingObserver. This is the foundation for Phase 2's work on interrupted operations:
1class _AppState extends State<App> with WidgetsBindingObserver {
2 @override
3 void initState() {
4 super.initState();
5 WidgetsBinding.instance.addObserver(this);
6 }
7
8 @override
9 void didChangeAppLifecycleState(AppLifecycleState state) {
10 if (state == AppLifecycleState.resumed) {
11 // e.g. refresh the session or data
12 }
13 }
14
15 @override
16 void dispose() {
17 WidgetsBinding.instance.removeObserver(this);
18 super.dispose();
19 }
20
21 @override
22 Widget build(BuildContext context) => const SizedBox();
23}
2.10 Form state and validation
Forms are the most common source of local state in business apps. Use Form with TextFormField and a GlobalKey<FormState>:
1class TransferForm extends StatefulWidget {
2 const TransferForm({super.key});
3
4 @override
5 State<TransferForm> createState() => _TransferFormState();
6}
7
8class _TransferFormState extends State<TransferForm> {
9 final _formKey = GlobalKey<FormState>();
10 final _amountController = TextEditingController();
11 final _accountController = TextEditingController();
12
13 @override
14 void dispose() {
15 _amountController.dispose();
16 _accountController.dispose();
17 super.dispose();
18 }
19
20 String? _validateAmount(String? value) {
21 if (value == null || value.trim().isEmpty) return 'Enter an amount';
22 final amount = double.tryParse(value);
23 if (amount == null) return 'Enter a valid number';
24 if (amount <= 0) return 'Amount must be greater than zero';
25 return null; // valid
26 }
27
28 void _submit() {
29 if (_formKey.currentState!.validate()) {
30 // safe to proceed
31 }
32 }
33
34 @override
35 Widget build(BuildContext context) {
36 return Form(
37 key: _formKey,
38 autovalidateMode: AutovalidateMode.onUserInteraction,
39 child: Column(
40 children: [
41 TextFormField(
42 controller: _accountController,
43 decoration: const InputDecoration(labelText: 'To account'),
44 textInputAction: TextInputAction.next,
45 validator: (v) =>
46 (v == null || v.length < 8) ? 'Account number is too short' : null,
47 ),
48 TextFormField(
49 controller: _amountController,
50 decoration: const InputDecoration(labelText: 'Amount'),
51 keyboardType: const TextInputType.numberWithOptions(decimal: true),
52 textInputAction: TextInputAction.done,
53 validator: _validateAmount,
54 onFieldSubmitted: (_) => _submit(),
55 ),
56 const SizedBox(height: 16),
57 FilledButton(onPressed: _submit, child: const Text('Send')),
58 ],
59 ),
60 );
61 }
62}
Validation tips:
- Keep validators as pure functions (string in, error out) so they are trivially unit-testable (see Part 3).
- Use
AutovalidateMode.onUserInteractionto avoid showing errors before the user has typed anything. - Client-side validation improves UX, but the server remains the authority. Always handle server-side validation errors too.
- For money, avoid
doublein production. Use integer minor units (cents/paisa) or a decimal package to prevent rounding errors.
2.11 Choosing the right scope: a checklist
Before creating state, ask:
- Is it needed by more than one widget? Lift it, or use a provider.
- Does it need to survive navigation? Put it above the route.
- Is it derived from other state? Compute it, do not store it. For example,
totalshould be calculated fromitems, not saved separately. - Does it need cleanup? Make sure someone disposes it.
Part 3: Unit Testing, Accessibility, Localization, and Keyboard Handling
These four topics share a theme: quality for every user in every situation. They are the difference between "it works on my phone" and "it works."
3.1 Testing
Flutter has three levels of tests:
- Unit tests: Test a function or class in isolation, with no UI. Fast and numerous.
- Widget tests: Render a widget (or a screen) in a test environment and simulate interaction. Fast, with no device needed.
- Integration tests: Run the whole app on a device or emulator. Slower, fewer, and focused on critical journeys.
A healthy suite has many unit tests, a good number of widget tests, and a few integration tests. This phase focuses on unit and widget tests.
Setup: flutter_test ships with the SDK. For mocking, add mocktail:
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^<latest>
Run your tests:
flutter test
flutter test test/validators_test.dart
flutter test --coverage
3.2 Unit tests
Start with pure logic. Here is a validator and its tests:
// lib/validators.dart
String? validateAmount(String? value) {
if (value == null || value.trim().isEmpty) return 'Enter an amount';
final amount = double.tryParse(value);
if (amount == null) return 'Enter a valid number';
if (amount <= 0) return 'Amount must be greater than zero';
return null;
}
1// test/validators_test.dart
2import 'package:flutter_test/flutter_test.dart';
3import 'package:my_app/validators.dart';
4
5void main() {
6 group('validateAmount', () {
7 test('rejects empty input', () {
8 expect(validateAmount(''), 'Enter an amount');
9 expect(validateAmount(null), 'Enter an amount');
10 });
11
12 test('rejects non-numeric input', () {
13 expect(validateAmount('abc'), 'Enter a valid number');
14 });
15
16 test('rejects zero and negative values', () {
17 expect(validateAmount('0'), isNotNull);
18 expect(validateAmount('-5'), isNotNull);
19 });
20
21 test('accepts a valid positive amount', () {
22 expect(validateAmount('250.50'), isNull);
23 });
24 });
25}
Notice the structure: Arrange, Act, Assert. Each test checks one behavior and has a descriptive name that reads like a sentence.
3.3 Testing state and async logic with mocks
The notifier from Part 2 depends on a repository. In tests we replace the real repository with a mock so we control the result and avoid network calls.
1import 'package:mocktail/mocktail.dart';
2import 'package:flutter_test/flutter_test.dart';
3
4class MockAccountRepository extends Mock implements AccountRepository {}
5
6void main() {
7 late MockAccountRepository repository;
8 late AccountsNotifier notifier;
9
10 setUp(() {
11 repository = MockAccountRepository();
12 notifier = AccountsNotifier(repository);
13 });
14
15 test('starts in loading state', () {
16 expect(notifier.state, isA<AccountsLoading>());
17 });
18
19 test('emits loaded state on success', () async {
20 when(() => repository.fetchAccounts())
21 .thenAnswer((_) async => [Account(id: '1', name: 'Savings', balance: 1000)]);
22
23 await notifier.load();
24
25 expect(notifier.state, isA<AccountsLoaded>());
26 expect((notifier.state as AccountsLoaded).accounts, hasLength(1));
27 });
28
29 test('emits failure state when the repository throws', () async {
30 when(() => repository.fetchAccounts()).thenThrow(Exception('boom'));
31
32 await notifier.load();
33
34 expect(notifier.state, isA<AccountsFailure>());
35 });
36
37 test('emits a timeout message on TimeoutException', () async {
38 when(() => repository.fetchAccounts()).thenThrow(TimeoutException('slow'));
39
40 await notifier.load();
41
42 final failure = notifier.state as AccountsFailure;
43 expect(failure.message, contains('timed out'));
44 });
45}
This is also why dependency injection matters (a major Phase 2 topic): the notifier receives its repository through the constructor, so it is trivially testable.
3.4 Widget tests
A widget test builds a widget, interacts with it, and checks the result:
1testWidgets('shows validation errors when the form is submitted empty',
2 (tester) async {
3 await tester.pumpWidget(
4 const MaterialApp(home: Scaffold(body: TransferForm())),
5 );
6
7 await tester.tap(find.text('Send'));
8 await tester.pump(); // rebuild after the tap
9
10 expect(find.text('Enter an amount'), findsOneWidget);
11});
12
13testWidgets('accepts a valid amount', (tester) async {
14 await tester.pumpWidget(
15 const MaterialApp(home: Scaffold(body: TransferForm())),
16 );
17
18 await tester.enterText(find.byType(TextFormField).last, '250');
19 await tester.tap(find.text('Send'));
20 await tester.pump();
21
22 expect(find.text('Enter an amount'), findsNothing);
23});
Useful tools:
find.text,find.byType,find.byKey,find.byIcon,find.bySemanticsLabeltester.tap,tester.enterText,tester.drag,tester.scrollUntilVisibletester.pump()advances one frame.tester.pumpAndSettle()waits until animations finish. AvoidpumpAndSettlewith infinite animations such as a looping progress indicator, because it will time out.
Testing every state of a screen: Provide a fake or mock that returns each state and assert what appears:
testWidgets('shows an error view with a retry button on failure', (tester) async {
final notifier = FakeAccountsNotifier(const AccountsFailure('Oops'));
await tester.pumpWidget(
ChangeNotifierProvider<AccountsNotifier>.value(
value: notifier,
child: const MaterialApp(home: AccountsScreen()),
),
);
expect(find.text('Oops'), findsOneWidget);
expect(find.text('Retry'), findsOneWidget);
});
Testing guidelines:
- Test behavior, not implementation details.
- Give important widgets a
Keyso tests can find them reliably. - Keep tests independent. Never let one test depend on another's leftovers (
setUpresets state). - Test the failure paths. Denied, empty, and timeout cases are where real bugs live.
- Do not chase 100% coverage. Cover the logic that matters, such as money, validation, and state transitions.
3.5 Accessibility
Accessibility (a11y) means everyone can use your app, including people who use screen readers (TalkBack on Android, VoiceOver on iOS), larger text, high contrast, or switch controls. For a banking app it is also frequently a compliance expectation.
a) Semantics: describe what widgets mean. Most built-in widgets already provide semantics. Add them when you build custom visuals or use icon-only controls.
1// Icon-only button: tell the screen reader what it does
2IconButton(
3 icon: const Icon(Icons.swap_horiz),
4 tooltip: 'Transfer money', // used as the accessible label
5 onPressed: onTransfer,
6)
7
8// Custom widget
9Semantics(
10 label: 'Savings account, balance 1,000 rupees',
11 button: true,
12 onTap: onOpen,
13 child: AccountCard(account: account),
14)
15
16// Merge fragments into one announcement
17MergeSemantics(
18 child: Row(children: [Text('Balance'), Text('Rs. 1,000')]),
19)
20
21// Hide decorative elements
22ExcludeSemantics(child: DecorativeDivider())
b) Touch target size. Interactive elements should be at least 48 x 48 logical pixels (Material guideline). Tiny tap targets are hard for many users.
ConstrainedBox(
constraints: const BoxConstraints(minWidth: 48, minHeight: 48),
child: InkWell(onTap: onTap, child: icon),
)
c) Text scaling. Users can increase system font size. Your layout must not clip or overflow.
- Avoid fixed heights on anything containing text.
- Use
Flexible/Expanded,Wrap, and scrollable parents. - Test at large scale factors:
testWidgets('does not overflow at 2x text scale', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(textScaler: TextScaler.linear(2.0)),
child: const AccountsScreen(),
),
),
);
expect(tester.takeException(), isNull); // no RenderFlex overflow
});
d) Color and contrast. Text should have enough contrast against its background (WCAG AA is 4.5:1 for normal text). Never use color alone to convey meaning. For example, pair red error text with an icon or message, since some users cannot distinguish red from green.
e) Focus order and labels for forms. Use proper labelText on inputs (not just hint text, which disappears) so screen readers announce the field purpose.
f) Automated guideline checks in tests:
testWidgets('meets accessibility guidelines', (tester) async {
final handle = tester.ensureSemantics();
await tester.pumpWidget(const MaterialApp(home: AccountsScreen()));
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
await expectLater(tester, meetsGuideline(iOSTapTargetGuideline));
await expectLater(tester, meetsGuideline(labeledTapTargetGuideline));
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
g) Test on a real device. Automated checks catch a lot, but nothing replaces turning on TalkBack or VoiceOver and navigating your own screen with your eyes closed. This is part of the Phase 1 mentor review.
3.6 Localization (l10n) and internationalization (i18n)
Localization means your app presents the right language, number format, date format, and text direction for each user. Even if you ship in one language today, never hardcode user-facing strings. Retrofitting later is expensive.
Setup:
# pubspec.yaml
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: any # use the version Flutter pins
flutter:
generate: true
# l10n.yaml (project root)
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
Define strings in ARB files:
// lib/l10n/app_en.arb
{
"@@locale": "en",
"transferTitle": "Transfer money",
"welcomeUser": "Welcome back, {name}",
"@welcomeUser": {
"placeholders": { "name": { "type": "String" } }
},
"accountCount": "{count, plural, =0{No accounts} =1{1 account} other{{count} accounts}}",
"@accountCount": {
"placeholders": { "count": { "type": "int" } }
}
}
// lib/l10n/app_ne.arb (Nepali)
{
"@@locale": "ne",
"transferTitle": "रकम सार्नुहोस्",
"welcomeUser": "स्वागत छ, {name}"
}
Run flutter pub get (or flutter gen-l10n) to generate AppLocalizations.
Wire it into the app:
MaterialApp.router(
routerConfig: router,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
);
Use it in widgets:
final l10n = AppLocalizations.of(context)!;
Text(l10n.transferTitle);
Text(l10n.welcomeUser('Indra'));
Text(l10n.accountCount(3)); // "3 accounts"
Format numbers, currency, and dates with intl, never by string concatenation:
import 'package:intl/intl.dart';
final locale = Localizations.localeOf(context).toString();
final money = NumberFormat.currency(locale: locale, symbol: 'Rs. ');
money.format(1250000.5); // "Rs. 1,250,000.50"
DateFormat.yMMMd(locale).format(DateTime.now());
Localization pitfalls:
- Do not build sentences by joining fragments (
'Hello ' + name + '!'). Word order differs by language. Use placeholders. - Plurals are not just "s". Use ICU plural syntax as shown above.
- Text length varies. German or Nepali strings may be much longer than English, so avoid fixed-width containers (this ties directly back to text-scaling tests).
- Right-to-left languages (Arabic, Hebrew) mirror the layout. Prefer
EdgeInsetsDirectional,AlignmentDirectional, andstart/endoverleft/right. - Test it: Pump a widget with each supported locale and verify the strings and absence of overflow.
testWidgets('renders Nepali title', (tester) async {
await tester.pumpWidget(
const MaterialApp(
locale: Locale('ne'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: TransferScreen(),
),
);
await tester.pumpAndSettle();
expect(find.text('रकम सार्नुहोस्'), findsOneWidget);
});
3.7 Keyboard handling
The on-screen keyboard is one of the biggest sources of mobile UI bugs: covered fields, overflow errors, and awkward flows.
a) Choose the right keyboard and action button:
TextFormField(
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next, // shows "next"
autofillHints: const [AutofillHints.email],
)
TextFormField(
keyboardType: const TextInputType.numberWithOptions(decimal: true),
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => _submit(),
)
Common keyboardType values: text, emailAddress, number, phone, url, multiline. Common actions: next, done, search, send.
b) Move focus between fields with FocusNode:
final _amountFocus = FocusNode();
TextFormField(
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => FocusScope.of(context).requestFocus(_amountFocus),
),
TextFormField(
focusNode: _amountFocus,
textInputAction: TextInputAction.done,
),
// and don't forget: _amountFocus.dispose();
Or simply use FocusScope.of(context).nextFocus().
c) Prevent the keyboard from covering content. Scaffold resizes its body when the keyboard opens (resizeToAvoidBottomInset defaults to true). The classic bug is a Column that overflows in the shrunken space. The fix is to make the content scrollable:
Scaffold(
body: SafeArea(
child: SingleChildScrollView(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
padding: EdgeInsets.fromLTRB(
16, 16, 16, 16 + MediaQuery.viewInsetsOf(context).bottom,
),
child: const TransferForm(),
),
),
)
MediaQuery.viewInsetsOf(context).bottom gives the keyboard height, which is useful when you need to pin a button above the keyboard or add extra padding.
d) Dismiss the keyboard when tapping outside:
GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: const TransferForm(),
)
e) Autofocus sparingly. autofocus: true pops the keyboard immediately and can be jarring. Use it only when typing is the screen's obvious purpose, such as a search page.
f) Hardware keyboards (tablets, desktop, web, accessibility). Support Tab navigation and shortcuts:
FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Form(/* fields */),
)
Shortcuts(
shortcuts: {
LogicalKeySet(LogicalKeyboardKey.enter): const ActivateIntent(),
},
child: /* ... */,
)
Keyboard checklist for every form screen:
- Correct
keyboardTypeandtextInputActionon each field - Focus moves forward logically and the last field submits
- No overflow when the keyboard is open (test on a small device)
- Keyboard dismisses on scroll or tap outside
- Validation messages remain visible and are not hidden by the keyboard
Part 4: Widget Composition, Keys, Scrolling, Themes, and Reusable Components
4.1 Composition over inheritance
Flutter's core idea: build complex UIs by composing small widgets, not by extending big ones. Smaller widgets are easier to read, test, reuse, and rebuild efficiently.
Before: one giant build method
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
// 120 lines of nested containers, texts, rows, and icons...
],
),
);
}
After: small, named widgets
Widget build(BuildContext context) {
return Scaffold(
appBar: const AccountsAppBar(),
body: Column(
children: const [
BalanceSummaryCard(),
QuickActionsRow(),
Expanded(child: RecentTransactionsList()),
],
),
);
}
Extract widgets as classes, not as helper methods:
// Avoid: a method that returns a widget
Widget _buildHeader() => Text('Accounts');
// Prefer: a widget class
class AccountsHeader extends StatelessWidget {
const AccountsHeader({super.key});
@override
Widget build(BuildContext context) => const Text('Accounts');
}
Why classes win:
- They can be
const, so Flutter skips rebuilding them entirely. - They have their own
BuildContext, sosetStateorwatchrebuilds only that subtree. - They get their own element in DevTools and are individually testable.
When to extract a widget:
- A section has a clear name ("transaction row")
- A piece repeats in more than one place
- A subtree has its own state or its own data dependencies
- The
buildmethod has grown past roughly 50 to 80 lines or nests deeper than you can comfortably read
4.2 Understanding and controlling rebuilds
Review the rebuild behavior from Phase 0, because Phase 1 puts it to work:
- Use
constconstructors wherever possible:const SizedBox(height: 16). - Keep
setStateas low in the tree as possible. Calling it on a huge screen widget rebuilds everything beneath it. - Pass the unchanging
childto builders such asAnimatedBuilderandValueListenableBuilderso it is not rebuilt. - Use
select(Provider) orref.watch(provider.select(...))(Riverpod) to listen to only what you need. - Do not do expensive work in
build. Compute it once (in state) or cache it.
Use Flutter DevTools (the Widget Inspector's rebuild tracking, and the Performance view) to confirm your assumptions rather than guessing.
4.3 Keys
A Key tells Flutter how to match old widgets to new ones when the tree changes. Without keys, Flutter matches widgets by type and position. That is fine for static layouts but causes bugs when widgets of the same type are reordered, inserted, or removed.
The classic bug: A list of stateful tiles (each with its own checkbox state). You delete the first item, and the state "jumps" to the wrong row, because Flutter matched by position.
// Without keys: state can attach to the wrong item after removal
ListView(
children: [for (final t in tasks) TaskTile(task: t)],
)
// With keys: each tile keeps its own state
ListView(
children: [for (final t in tasks) TaskTile(key: ValueKey(t.id), task: t)],
)
Types of keys:
ValueKey(value): Identity based on a value such as an ID. The most common choice for list items.ObjectKey(object): Identity based on an object instance.UniqueKey(): A new identity every time it is built. This forces the widget to be recreated on every build, so use it carefully.GlobalKey: Unique across the whole app. It lets you access a widget's state or position from elsewhere (for exampleGlobalKey<FormState>). It is powerful but expensive, so use it sparingly.PageStorageKey: Preserves scroll position (seen in Part 1).
Rules of thumb:
- Add keys to items in dynamic lists, especially those with state, animations, or text fields.
- Use stable, unique identifiers (database IDs), not the list index, as key values when the list can reorder.
- You usually do not need keys for static, non-reordering children.
- Put keys on the topmost widget of the item you want to track.
Keys for testing: Key('submit_button') lets tests find widgets robustly without depending on text that may be localized.
FilledButton(
key: const Key('submit_button'),
onPressed: _submit,
child: Text(l10n.send),
)
// In a test
await tester.tap(find.byKey(const Key('submit_button')));
4.4 Scrolling
Rule one: use lazy builders for long or unknown-length lists.
// Builds every item up front: fine for 10 items, terrible for 10,000
ListView(children: items.map(ItemTile.new).toList());
// Builds only what is visible
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) => ItemTile(items[index]),
);
Also useful: ListView.separated (adds dividers), GridView.builder, and PageView.
Rule two: never put an unbounded scrollable inside another scrollable in the same direction without constraining it. The famous "Vertical viewport was given unbounded height" error comes from a ListView inside a Column. Fixes:
// Give the list the remaining space
Column(
children: [
const Header(),
Expanded(child: ListView.builder(/* ... */)),
],
)
// Or, for a small list inside a scroll view
ListView(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
children: /* ... */,
)
Be careful with shrinkWrap: true on long lists, because it disables laziness and hurts performance.
Rule three: use slivers for mixed scrolling content. CustomScrollView lets headers, lists, and grids scroll as one surface, with collapsing app bars and pinned headers:
CustomScrollView(
slivers: [
const SliverAppBar(
pinned: true,
expandedHeight: 160,
flexibleSpace: FlexibleSpaceBar(title: Text('Accounts')),
),
SliverList.builder(
itemCount: accounts.length,
itemBuilder: (context, i) => AccountTile(account: accounts[i]),
),
const SliverToBoxAdapter(child: Footer()),
],
)
Controlling and observing scroll position:
final _controller = ScrollController();
@override
void initState() {
super.initState();
_controller.addListener(() {
if (_controller.position.pixels >=
_controller.position.maxScrollExtent - 200) {
loadNextPage(); // infinite scroll / pagination
}
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Pull to refresh:
RefreshIndicator(
onRefresh: () => context.read<AccountsNotifier>().load(),
child: ListView.builder(/* ... */),
)
Scroll performance tips:
- Use
itemExtentorprototypeItemwhen all rows have the same height. It speeds up layout. - Keep item widgets cheap and
constwhere possible. - Avoid heavy work (image decoding, parsing) inside
itemBuilder. - Use
cacheExtentcarefully, as larger values build more offscreen items.
4.5 Themes
A theme centralizes your app's look so that changing the brand color or font means editing one place, not 80 widgets.
Define a theme:
1final lightTheme = ThemeData(
2 useMaterial3: true,
3 colorScheme: ColorScheme.fromSeed(
4 seedColor: const Color(0xFF0B5FFF),
5 brightness: Brightness.light,
6 ),
7 textTheme: const TextTheme(
8 headlineMedium: TextStyle(fontSize: 28, fontWeight: FontWeight.w700),
9 bodyMedium: TextStyle(fontSize: 16),
10 ),
11 inputDecorationTheme: const InputDecorationTheme(
12 border: OutlineInputBorder(),
13 ),
14 filledButtonTheme: FilledButtonThemeData(
15 style: FilledButton.styleFrom(
16 minimumSize: const Size.fromHeight(48),
17 shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
18 ),
19 ),
20);
21
22final darkTheme = ThemeData(
23 useMaterial3: true,
24 colorScheme: ColorScheme.fromSeed(
25 seedColor: const Color(0xFF0B5FFF),
26 brightness: Brightness.dark,
27 ),
28);
29
30MaterialApp.router(
31 theme: lightTheme,
32 darkTheme: darkTheme,
33 themeMode: ThemeMode.system, // follow the device setting
34 routerConfig: router,
35);
Use theme values instead of hardcoding:
// BAD: hardcoded, ignores dark mode and branding changes
Text('Balance', style: TextStyle(color: Colors.black, fontSize: 18));
// GOOD: theme-driven
Text('Balance', style: Theme.of(context).textTheme.titleMedium);
Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
)
Custom fonts (configured in pubspec.yaml, as covered in Phase 0, then set in the theme):
flutter:
fonts:
- family: Inter
fonts:
- asset: assets/fonts/Inter-Regular.ttf
- asset: assets/fonts/Inter-Bold.ttf
weight: 700
ThemeData(fontFamily: 'Inter')
Theme extensions for your own design tokens (for example, success and warning colors that Material does not define):
1@immutable
2class AppColors extends ThemeExtension<AppColors> {
3 const AppColors({required this.success, required this.warning});
4
5 final Color success;
6 final Color warning;
7
8 @override
9 AppColors copyWith({Color? success, Color? warning}) =>
10 AppColors(success: success ?? this.success, warning: warning ?? this.warning);
11
12 @override
13 AppColors lerp(ThemeExtension<AppColors>? other, double t) {
14 if (other is! AppColors) return this;
15 return AppColors(
16 success: Color.lerp(success, other.success, t)!,
17 warning: Color.lerp(warning, other.warning, t)!,
18 );
19 }
20}
21
22// Register
23ThemeData(extensions: const [AppColors(success: Colors.green, warning: Colors.orange)]);
24
25// Use
26final colors = Theme.of(context).extension<AppColors>()!;
Theme guidelines:
- Define spacing, radii, and colors once. Do not scatter magic numbers.
- Test both light and dark modes, including contrast.
- Override the theme locally with the
Themewidget only when a subtree genuinely needs it. - Prefer
colorSchemeroles (primary,onPrimary,error,surface) over rawColorvalues so contrast pairs stay correct.
4.5.1 Responsive layouts
Themes handle look; layout must also adapt to size. Use LayoutBuilder or MediaQuery.sizeOf:
LayoutBuilder(
builder: (context, constraints) {
final isWide = constraints.maxWidth >= 600;
return isWide
? Row(children: [
const SizedBox(width: 280, child: AccountsList()),
const Expanded(child: AccountDetail()),
])
: const AccountsList();
},
)
Prefer MediaQuery.sizeOf(context) over MediaQuery.of(context).size, because it rebuilds only when the size changes, not on every media-query change such as the keyboard.
4.6 Reusable components
Reusable components are the payoff for everything above: composition, themes, and accessibility, packaged once and used everywhere. A good shared component:
- Has a small, clear API with required parameters for what must be supplied and sensible defaults for the rest.
- Takes data and callbacks rather than reaching into global state. This keeps it presentation-only and trivial to test.
- Uses the theme and never hardcodes colors or text styles.
- Handles its own states (loading, disabled, error).
- Is accessible and localizable by default.
Example: a reusable primary button with a loading state
1class AppButton extends StatelessWidget {
2 const AppButton({
3 super.key,
4 required this.label,
5 required this.onPressed,
6 this.isLoading = false,
7 this.icon,
8 });
9
10 final String label;
11 final VoidCallback? onPressed; // null = disabled
12 final bool isLoading;
13 final IconData? icon;
14
15 @override
16 Widget build(BuildContext context) {
17 final enabled = onPressed != null && !isLoading; // prevents double tap
18
19 return Semantics(
20 button: true,
21 enabled: enabled,
22 label: isLoading ? '$label, loading' : label,
23 child: FilledButton(
24 onPressed: enabled ? onPressed : null,
25 child: isLoading
26 ? const SizedBox(
27 height: 20,
28 width: 20,
29 child: CircularProgressIndicator(strokeWidth: 2),
30 )
31 : Row(
32 mainAxisSize: MainAxisSize.min,
33 children: [
34 if (icon != null) ...[Icon(icon, size: 18), const SizedBox(width: 8)],
35 Text(label),
36 ],
37 ),
38 ),
39 );
40 }
41}
Usage becomes tidy and consistent everywhere:
AppButton(
label: l10n.send,
isLoading: state.isSubmitting,
onPressed: _submit,
)
Example: reusable state views
Every screen needs loading, empty, and error states. Build them once:
1class EmptyView extends StatelessWidget {
2 const EmptyView({super.key, required this.message, this.icon = Icons.inbox_outlined});
3
4 final String message;
5 final IconData icon;
6
7 @override
8 Widget build(BuildContext context) {
9 final theme = Theme.of(context);
10 return Center(
11 child: Padding(
12 padding: const EdgeInsets.all(24),
13 child: Column(
14 mainAxisSize: MainAxisSize.min,
15 children: [
16 Icon(icon, size: 48, color: theme.colorScheme.outline),
17 const SizedBox(height: 12),
18 Text(message, style: theme.textTheme.bodyLarge, textAlign: TextAlign.center),
19 ],
20 ),
21 ),
22 );
23 }
24}
25
26class ErrorView extends StatelessWidget {
27 const ErrorView({super.key, required this.message, required this.onRetry});
28
29 final String message;
30 final VoidCallback onRetry;
31
32 @override
33 Widget build(BuildContext context) {
34 return Center(
35 child: Column(
36 mainAxisSize: MainAxisSize.min,
37 children: [
38 Icon(Icons.error_outline, color: Theme.of(context).colorScheme.error),
39 const SizedBox(height: 8),
40 Text(message, textAlign: TextAlign.center),
41 const SizedBox(height: 12),
42 OutlinedButton(onPressed: onRetry, child: const Text('Retry')),
43 ],
44 ),
45 );
46 }
47}
Organizing shared components:
lib/
core/
theme/ app_theme.dart, app_colors.dart
widgets/ app_button.dart, empty_view.dart, error_view.dart
features/
accounts/
accounts_screen.dart
accounts_notifier.dart
widgets/ account_tile.dart
transfer/
transfer_screen.dart
transfer_form.dart
Feature-specific widgets live inside their feature. Only genuinely shared widgets go into core/widgets. Do not promote something to "shared" until a second feature needs it, to avoid premature abstraction.
Test your components. A reusable component with a widget test is one you can change confidently:
testWidgets('AppButton ignores taps while loading', (tester) async {
var taps = 0;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: AppButton(label: 'Send', isLoading: true, onPressed: () => taps++),
),
));
await tester.tap(find.byType(FilledButton));
expect(taps, 0);
});
Putting It All Together: A Feature Walkthrough
Here is how the four pillars combine in one feature, the Transfer flow.
- Navigation:
/accounts/:idopens the detail screen via a path parameter. A "Transfer" button doescontext.push('/transfer?from=42'). On success the screen pops with a result, and the list refreshes. - State: A
TransferNotifierowns an immutableTransferState(amount, source, status). It exposessubmit(), which moves throughidle,submitting, thensuccessorfailure. The state is scoped to the transfer route and disposed when the user leaves. - Quality:
- Unit tests cover the validator and notifier transitions (including timeout).
- Widget tests cover the form's error messages and the double-submit guard.
- Semantics, tap targets, and a 2x text-scale test pass.
- All strings live in ARB files, and amounts are formatted with
intl. - The keyboard flow (Next, Done, scroll, dismiss) works on a small device.
- UI: The screen is composed of
AccountPicker,AmountField, andAppButton. All of them are themed, keyed where dynamic, and wrapped with the sharedErrorViewandEmptyView.
When all four are done, you have a feature that is navigable, predictable, tested, inclusive, and maintainable.
Phase 1 Mentorship Builds (Self-Check)
Use these exercises as a self-assessment. Each maps to what you will demonstrate in mentor reviews.
- Navigation and forms: Add navigation, form validation, and interactive state to the sample app.
- State boundaries: Implement shared state and reusable components, with validated forms. Review widget boundaries, state placement, and rebuild behavior.
- All the states: Demonstrate loading, success, empty, and error states for a data screen.
- Tests: Add unit and widget tests for validators, state transitions, and at least one screen.
- Inclusive UI: Support text scaling, localization (two languages), and keyboard interactions. Verify accessibility on a real device.
- Layout and lifecycle issues: Be ready to explain and fix an overflow, a lost-state bug, and a missing
dispose.
Common Mistakes Checklist
- Using
contextafterawaitwithoutcontext.mounted - Passing whole objects through
extrainstead of IDs - Storing derived data instead of computing it
- Mutating state in place instead of replacing it
- Modeling async state with several unrelated booleans
- Forgetting the empty state
- Not disposing controllers, focus nodes, and subscriptions
- Giant
buildmethods and helper methods that return widgets - Using list index as a key in reorderable lists
-
ListViewinColumnwithoutExpanded - Hardcoded colors, text styles, and user-facing strings
- Fixed heights on text containers
- Tap targets smaller than 48 x 48
- Forms that overflow when the keyboard opens
- Only testing the happy path
Key Takeaways
- Navigation: Pass IDs, not objects. Use a router for deep links and guards. Preserve tab state intentionally.
- State: One owner per piece of state. Keep it immutable. Model loading, data, empty, and error explicitly. Always dispose what you create.
- Quality: Tests, accessibility, localization, and keyboard handling are part of the feature, not a polish step at the end.
- UI: Compose small widgets, use keys for dynamic lists, use lazy scrolling, drive visuals from the theme, and build reusable components that are accessible and tested.
What's Next: Phase 2
Phase 1 teaches you to build a screen-level feature that is correct and polished. In Phase 2, we scale up to feature architecture: separating UI, state, and data layers, dependency injection, repository abstractions, local persistence, networking with mock APIs, and device capabilities such as permissions, deep links, notifications, and biometrics, including the denied, cancelled, and unavailable scenarios.
If Phase 1 is about building screens that work, Phase 2 is about building features that survive the real world.
Thanks for reading. If this was useful, follow along for Phase 2, and feel free to share the tricky Phase 1 bugs you have hit in the comments.