Sub topic 11
Organizing your app into widgets and files
This chapter assumes you can write a StatelessWidget, you know how MaterialApp, Scaffold, and AppBar nest, and you have used named routes, a drawer, and a SnackBar at least once. The code so far has lived in one file. Here you split it into small widget classes and a folder layout that stays readable as the app grows.
Why structure matters
One file with five screens works until you need to change one of them. At that point you scroll through hundreds of lines to find the right build method, and every edit risks touching something unrelated.
Splitting an app gives you three things:
- Findability. The Settings screen is in
settings_page.dart, not somewhere inmain.dart. - Smaller rebuilds. A widget class with a
constconstructor can be skipped by the framework when its inputs have not changed. - Correct context. Each widget class gets its own
BuildContext. Several framework lookups, such asNavigator.of(context), depend on where that context sits in the tree.
A folder layout for a small app
Flutter creates lib/main.dart for you. For an app with a theme, a few screens, and one shared widget, this layout is enough:
lib/
main.dart
app.dart
routes.dart
theme/
app_theme.dart
screens/
home_page.dart
settings_page.dart
widgets/
app_drawer.dart
empty_state.dartEach file has one job:
| File | Responsibility |
|---|---|
| `main.dart` | Entry point. Calls `runApp` and nothing else. |
| `app.dart` | The `MaterialApp`: title, themes, route table. |
| `routes.dart` | Route name constants. |
| `theme/app_theme.dart` | `ThemeData` objects built from a seed color. |
| `screens/` | One widget per full screen, each returning a `Scaffold`. |
| `widgets/` | Pieces used by more than one screen, or large enough to deserve a name. |
The examples below assume the package is named inbox_app in pubspec.yaml. Change the import prefix if yours differs.
Before the diagram, one more rule. Dependencies should point in one direction: main.dart imports the app, the app imports screens and the theme, and screens import shared widgets. Nothing in widgets/ should import a screen.
Step 1: keep main.dart tiny
main.dart only starts the app:
import 'package:flutter/material.dart';
import 'package:inbox_app/app.dart';
void main() => runApp(const InboxApp());Keeping it this small means a test can build InboxApp directly, without going through main.
Step 2: give the app root its own class
InboxApp holds the MaterialApp. It is separate from every screen on purpose, and the reason is covered in the "Context" section below.
import 'package:flutter/material.dart';
import 'package:inbox_app/routes.dart';
import 'package:inbox_app/screens/home_page.dart';
import 'package:inbox_app/screens/settings_page.dart';
import 'package:inbox_app/theme/app_theme.dart';
class InboxApp extends StatelessWidget {
const InboxApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Inbox',
theme: AppTheme.light,
darkTheme: AppTheme.dark,
themeMode: ThemeMode.system,
initialRoute: AppRoutes.home,
routes: {
AppRoutes.home: (context) => const HomePage(),
AppRoutes.settings: (context) => const SettingsPage(),
},
);
}
}This file is the one place that knows every screen. Adding a screen means one new import and one new map entry.
Step 3: move the theme and route names out
Route names written as raw strings are easy to mistype. A typo in '/setings' fails only at runtime, when you tap the button. Constants turn that into a compile error.
class AppRoutes {
AppRoutes._();
static const home = '/';
static const settings = '/settings';
}The private constructor stops anyone from creating an instance of a class that only holds constants.
The theme moves into its own file, using the seed-color approach from the theming chapter:
import 'package:flutter/material.dart';
class AppTheme {
AppTheme._();
static const Color _seed = Colors.teal;
static final ThemeData light = ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: _seed),
useMaterial3: true,
);
static final ThemeData dark = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: _seed,
brightness: Brightness.dark,
),
useMaterial3: true,
);
}Changing the brand color is now a one-line edit in one file.
> Note on cycles: routes.dart holds only names. If it also held the route table, it would import the screens, and the screens would import it back for the names. Dart allows circular imports, but they make the code harder to follow. Keeping the names separate from the table avoids the cycle.
Step 4: screens and shared widgets
A screen is a widget that returns a Scaffold. It owns the appBar, the body, and any floatingActionButton. Pieces that other screens might reuse go in widgets/.
First, a shared widget for the empty state:
import 'package:flutter/material.dart';
class EmptyState extends StatelessWidget {
const EmptyState({super.key, required this.message, this.icon});
final String message;
final IconData? icon;
@override
Widget build(BuildContext context) {
final textStyle = Theme.of(context).textTheme.bodyLarge;
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null) Icon(icon, size: 48),
const SizedBox(height: 8),
Text(message, style: textStyle),
],
),
);
}
}The widget takes everything it needs through its constructor and reads the theme from context. It has no knowledge of which screen shows it.
Next, the drawer, extracted because its list of destinations is long enough to hide the screen's own layout:
import 'package:flutter/material.dart';
import 'package:inbox_app/routes.dart';
class AppDrawer extends StatelessWidget {
const AppDrawer({super.key});
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: [
const DrawerHeader(child: Text('Menu')),
ListTile(
leading: const Icon(Icons.settings),
title: const Text('Settings'),
onTap: () {
Navigator.pop(context);
Navigator.pushNamed(context, AppRoutes.settings);
},
),
],
),
);
}
}Then the home screen, which now reads as a short description of the page:
import 'package:flutter/material.dart';
import 'package:inbox_app/widgets/app_drawer.dart';
import 'package:inbox_app/widgets/empty_state.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inbox')),
drawer: const AppDrawer(),
body: const EmptyState(message: 'No messages', icon: Icons.inbox),
floatingActionButton: FloatingActionButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Compose tapped')),
);
},
child: const Icon(Icons.edit),
),
);
}
}The settings screen follows the same shape:
import 'package:flutter/material.dart';
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: const Center(child: Text('Settings go here')),
);
}
}Because SettingsPage is pushed on top of the home route, its AppBar shows a back button without any extra code.
Context: why the app root is its own class
Navigator.of(context), Theme.of(context), and ScaffoldMessenger.of(context) all search upward from context for an ancestor. The Navigator, the Theme, and the ScaffoldMessenger are all created by MaterialApp. They sit below it in the tree, never above it.
The context passed to InboxApp.build belongs to InboxApp, which is above the MaterialApp it returns. A lookup from that context finds nothing. If you wrote this inside the same build that creates the MaterialApp:
MaterialApp(
home: ElevatedButton(
onPressed: () => Navigator.of(context).pushNamed('/settings'),
child: const Text('Open'),
),
)you would get "Navigator operation requested with a context that does not include a Navigator". Moving the button into its own widget class gives it a context below MaterialApp, and the lookup works. This is the practical reason MaterialApp lives in one class and each screen lives in another.
The same effect applies inside a screen. In HomePage, the context passed to build is above the Scaffold that HomePage creates. Calling Scaffold.of(context) there fails for that reason. ScaffoldMessenger.of(context) works because the messenger comes from MaterialApp, which is above HomePage.
Widget classes versus helper methods
You can split a long build in two ways: into private methods like _buildHeader(), or into separate widget classes. They look similar but behave differently.
| Aspect | Helper method | Widget class |
|---|---|---|
| `const` constructor | Not possible | Possible, so rebuilds can be skipped |
| Own `BuildContext` | No, shares the parent's | Yes, sits at its own place in the tree |
| Rebuild scope | Rebuilds whenever the parent does | Rebuilds only when its inputs change or its own state changes |
| Reuse across files | Awkward | Import and use |
| Testing in isolation | Hard | Pump the widget alone |
Prefer widget classes for anything bigger than a few lines. A private method is fine for a short, one-off fragment that needs no const and no separate context.
When to split, and when not to
Create a new widget class when at least one of these is true:
- The same layout appears in two or more places.
- The
buildmethod no longer fits on one screen of your editor. - The piece has its own state or needs its own
context. - You can name it with a noun, such as
AppDrawerorEmptyState.
Do not split just to reach a line count. A widget that exists only to wrap one Text adds a file and an import without making anything clearer.
Choosing a folder strategy
The layout above groups files by kind: screens together, widgets together. Larger apps often group by feature instead.
| Strategy | Layout | Works best when |
|---|---|---|
| By kind | `screens/`, `widgets/`, `theme/` | The app has fewer than about ten screens. |
| By feature | `inbox/`, `settings/`, each with its own screens and widgets | Several people work on separate parts, or features may be removed. |
Move to feature folders when you notice that a change to one feature touches files in three different top-level folders. Shared items such as the theme and AppDrawer stay in a common folder.
Common errors
- Importing with relative paths that climb out of
lib/. Usepackage:inbox_app/...imports. They work the same from any file and survive moves. - Putting a screen inside
widgets/. If a widget returns its ownScaffold, it is a screen. Keep that distinction so you know where to look. - Forgetting
const.const HomePage()in the route table lets Flutter reuse the instance. The analyzer'sprefer_const_constructorslint will point out missing ones. - Calling
Navigator.pop(context)in the drawer and then using a stale context. InAppDrawer, the context still belongs to the drawer whenpushNamedruns, which works. Be careful if you addawaitbetween the two calls, because you would then need to checkcontext.mountedfirst. - Circular imports between screens. If
home_page.dartimportssettings_page.dartand the reverse, move the shared names or helpers into a third file.
Checking your work
After the split, the app should behave the same as before:
- Run the app. The Inbox screen shows the empty state and a menu icon in the app bar.
- Swipe from the left edge or tap the menu icon. Tap Settings. The drawer closes and the Settings screen opens with a back button.
- Go back and tap the edit button. A snackbar appears.
- Switch your device to dark mode. The teal scheme changes to its dark variant.
If any step fails, check the import lines at the top of the file involved first.
Exercise
A teammate puts a TextButton directly inside the home: argument of a MaterialApp, in the same build method that returns the MaterialApp. Its onPressed calls Navigator.of(context).pushNamed('/settings'). It throws "Navigator operation requested with a context that does not include a Navigator". Why does this happen, and how do you fix it by restructuring the code?
Show answer
The context in that build method belongs to the widget that creates the MaterialApp, so it is above the Navigator that MaterialApp builds. Navigator.of searches upward from the context and finds none. The fix is to move the button into its own widget class, such as a HomePage, and use the context from that class's build method. That context sits below MaterialApp, so the lookup finds the Navigator.
Exercise
You have a SettingsPage and a ProfilePage, and both need the same row layout showing an icon, a title, and a switch. Where should the row live, what kind of Dart construct should it be, and which files import it?
Show answer
Make it a widget class, for example SettingToggleRow, in lib/widgets/setting_toggle_row.dart, with a const constructor taking the icon, title, value, and onChanged callback. Both settings_page.dart and profile_page.dart import it with package:inbox_app/widgets/setting_toggle_row.dart. It must not import either screen, so imports keep pointing from screens to widgets.