Sub topic 2
MaterialApp: the root of a Material app
This chapter explains what MaterialApp sets up, which of its parameters you will use most, and which errors come from misplacing it. It assumes you can read basic Dart (classes, constructors, named parameters), can run a Flutter app, and know how StatelessWidget and build work. Later chapters cover Scaffold, AppBar, and theming in detail, so this chapter only introduces them.
What MaterialApp is responsible for
MaterialApp is a convenience widget. It wraps a lower-level widget called WidgetsApp and adds the things a Material Design app needs. In practice it creates, once and for the whole app:
- A
Navigator, which holds the stack of screens (routes). - A
Theme, which supplies colors, text styles, and component styles. MaterialLocalizations, which supplies translated strings for built-in widgets such as date pickers and back-button tooltips.- A
ScaffoldMessenger, which manages snack bars across screens. - Default scroll behavior, text direction, and an
Overlayfor tooltips and menus. - A
MediaQuery, which reports screen size, padding, and text scale.
Every screen in your app sits below MaterialApp in the widget tree. Widgets such as Scaffold and AppBar find the theme, navigator, and messenger by walking up from their own BuildContext. If a widget is above MaterialApp, it cannot find any of them.
The minimal app
This is the smallest useful skeleton. MyApp is the root, MaterialApp configures the app, and HomePage is the first screen.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo',
home: const HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: const Center(child: Text('Hello, Flutter')),
);
}
}Three things to notice:
MaterialAppis notconsthere. The constructor itself could be called withconstonly if every argument were constant, and that is rarely worth the constraint. The widgets you pass in, such asHomePage, can beconst.homeis a widget, not a function. Flutter wraps it in a route named/for you.titleis not shown in the app bar. The operating system uses it, for example in the task switcher on Android or the browser tab on the web. The text in the app bar comes from theAppBarwidget.
The parameters you will use most
MaterialApp has many parameters. This table covers the ones that matter in a typical app.
| Parameter | Type | Purpose |
|---|---|---|
| `title` | `String` | Name the OS shows for the app. |
| `home` | `Widget?` | The screen for the `/` route. |
| `routes` | `Map<String, WidgetBuilder>` | Named routes: path to screen builder. |
| `initialRoute` | `String?` | Route to show first. Defaults to `/`. |
| `onGenerateRoute` | `RouteFactory?` | Builds routes not found in `routes`, for example routes with arguments. |
| `onUnknownRoute` | `RouteFactory?` | Fallback when nothing else matches. Use it for a "not found" screen. |
| `theme` | `ThemeData?` | Light theme. |
| `darkTheme` | `ThemeData?` | Theme used when dark mode applies. |
| `themeMode` | `ThemeMode` | `system`, `light`, or `dark`. Defaults to `system`. |
| `navigatorKey` | `GlobalKey<NavigatorState>?` | Lets you reach the navigator without a `BuildContext`. |
| `localizationsDelegates` and `supportedLocales` | lists | Enable translations. |
| `builder` | `TransitionBuilder?` | Wraps every screen. It sits above the `Navigator` but below the `Theme` and `MediaQuery`. |
| `debugShowCheckedModeBanner` | `bool` | Set to `false` to hide the "DEBUG" ribbon. |
There is also MaterialApp.router, which takes a routerConfig instead of home and routes. It is used with packages such as go_router or the Router API. This tutorial uses the simpler Navigator setup with named routes.
Theme parameters
theme and darkTheme each take a ThemeData. The ColorScheme.fromSeed constructor generates a full, consistent set of colors from one seed color. themeMode decides which of the two is active.
MaterialApp(
title: 'Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.teal,
brightness: Brightness.dark,
),
useMaterial3: true,
),
themeMode: ThemeMode.system,
home: const HomePage(),
)Details that cause confusion:
- With
ThemeMode.system, Flutter picksthemeordarkThemebased on the device setting. If you providedarkThemebut leavethemeModeat its default, it still follows the system. - If you set
themeMode: ThemeMode.darkbut nodarkTheme, Flutter falls back to the default dark theme, not a dark version of yourtheme. Always give both. - In recent Flutter versions, Material 3 is the default, so
useMaterial3: trueis redundant there. Writing it explicitly is harmless and makes older SDKs behave the same. - The theme is read with
Theme.of(context). Thecontextmust be belowMaterialApp, as the next sections show.
Home screen and named routes
You can navigate with home alone, or you can register named routes.
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => const HomePage(),
'/settings': (context) => const SettingsPage(),
},
)Open a route by name from any widget below MaterialApp:
IconButton(
icon: const Icon(Icons.settings),
onPressed: () => Navigator.pushNamed(context, '/settings'),
)When SettingsPage is pushed on top of HomePage, its AppBar shows a back button on its own. The AppBar checks whether the route can be popped and adds the button if so. You write no code for it.
Rules that trip people up:
- Do not define both
homeand a'/'entry inroutes. Flutter asserts in debug mode because the two would both claim the same route. initialRoutedefaults to/. If you set it to another route name, Flutter pushes that route first and may also build the routes leading to it. For example,/a/bbuilds/,/a, and/a/b.- Names are plain strings. A typo such as
'/setings'is not a compile error. At run time it goes toonGenerateRouteand thenonUnknownRoute. If neither handles it, you get an error in debug mode. Define constants for route names to avoid this. routesbuilders receive only aBuildContext. To pass arguments, useNavigator.pushNamed(context, '/detail', arguments: id)and read them withModalRoute.of(context)!.settings.arguments, or handle the route inonGenerateRoute.
Here is a fallback for unknown routes:
MaterialApp(
routes: {
'/': (context) => const HomePage(),
},
onUnknownRoute: (settings) => MaterialPageRoute<void>(
builder: (context) => Scaffold(
appBar: AppBar(title: const Text('Not found')),
body: Center(child: Text('No route for ${settings.name}')),
),
),
)Common error: using the wrong context
The most common MaterialApp mistake is using a BuildContext from above it. A BuildContext identifies a position in the tree, and Navigator.of(context) searches upward from that position. The MaterialApp.build method's own context belongs to the widget that contains MaterialApp, so it is above the Navigator that MaterialApp creates.
This code compiles but fails when you tap the button:
import 'package:flutter/material.dart';
void main() => runApp(const BrokenApp());
class BrokenApp extends StatelessWidget {
const BrokenApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
// This context belongs to BrokenApp, above MaterialApp.
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => const Scaffold(body: Text('Next')),
),
),
child: const Text('Go'),
),
),
),
);
}
}Flutter reports: "Navigator operation requested with a context that does not include a Navigator." The same cause produces errors such as "No MaterialLocalizations found" and failed ScaffoldMessenger.of(context) or Theme.of(context) lookups.
The fix is to move the screen into its own widget. Its build method then receives a context that is below MaterialApp:
import 'package:flutter/material.dart';
void main() => runApp(const FixedApp());
class FixedApp extends StatelessWidget {
const FixedApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: StartPage());
}
}
class StartPage extends StatelessWidget {
const StartPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => const Scaffold(body: Center(child: Text('Next'))),
),
),
child: const Text('Go'),
),
),
);
}
}A Builder widget also gives you a fresh context, but a separate widget class is easier to read and test.
Edge cases and design decisions
One MaterialApp per app. Nest a second MaterialApp only if you need a fully separate navigation stack and theme, for example in an embedded preview. A nested one creates its own Navigator, so the back button and Navigator.of behave differently inside it. For most apps, use one MaterialApp and push routes.
Hot reload and the root. Hot reload keeps state and rebuilds widgets. Changing home while the app is running does not replace the current screen, because the Navigator already holds a route. Use hot restart to see a new home or initialRoute.
Changing the theme at run time. MaterialApp rebuilds when its parameters change. To let users switch themes, hold a ThemeMode in state above MaterialApp and pass it to themeMode. Because that state must live above MaterialApp, the widget that owns it is usually a StatefulWidget at the root, or a state-management solution you add later.
Keep the root small. MyApp.build should describe app-wide configuration only: title, theme, routes. Screens belong in their own classes. This keeps the root readable and keeps the context rule above easy to follow. A later chapter covers how to split these into files.
Cupertino apps. CupertinoApp is the iOS-style equivalent. Material widgets such as Scaffold expect a MaterialApp ancestor, or at least Material and MaterialLocalizations widgets above them. If you mix the two, you must supply those yourself.
Quick reference
runApp(MyApp())makesMyAppthe root of the widget tree.MaterialAppprovides theme, navigation, localization, media information, and the snack bar manager to everything below it.- Set
title, then eitherhomeorroutes(nothomeplus a'/'route), thentheme,darkTheme, andthemeMode. - Screens are widgets below
MaterialApp. Each usually returns aScaffold. - Use a context from below
MaterialAppfor any.of(context)lookup.
Exercise
Your app has MyApp extends StatelessWidget, whose build returns MaterialApp(home: Scaffold(floatingActionButton: FloatingActionButton(onPressed: () => ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Hi')))))). Tapping the button throws an error about not finding a ScaffoldMessenger. Explain why it happens and give two ways to fix it. Also state what happens if you add darkTheme but set themeMode: ThemeMode.dark without ever setting theme.
Show answer
The context used in onPressed is MyApp.build's context. It sits above MaterialApp, which is the widget that creates the ScaffoldMessenger, so the upward search finds none. Fix 1: move the Scaffold into its own widget class (for example HomePage) and use that widget's build context. Fix 2: wrap the button in a Builder and use the builder's context. Setting themeMode: ThemeMode.dark with darkTheme and no theme still works, because dark mode uses darkTheme. The unset theme only matters if the mode switches to light or the system chooses light, and then Flutter falls back to the default light theme. Providing both themes avoids that mismatch.