MaterialApp class - material library (original) (raw)

An application that uses Material Design.

A convenience widget that wraps a number of widgets that are commonly required for Material Design applications. It builds upon a WidgetsApp by adding material-design specific functionality, such as AnimatedTheme andGridPaper.

MaterialApp configures its WidgetsApp.textStyle with an ugly red/yellow text style that's intended to warn the developer that their app hasn't defined a default text style. Typically the app's Scaffold builds a Material widget whose default Material.textStyle defines the text style for the entire scaffold.

The MaterialApp configures the top-level Navigator to search for routes in the following order:

  1. For the / route, the home property, if non-null, is used.
  2. Otherwise, the routes table is used, if it has an entry for the route.
  3. Otherwise, onGenerateRoute is called, if provided. It should return a non-null value for any valid route not handled by home and routes.
  4. Finally if all else fails onUnknownRoute is called.

If a Navigator is created, at least one of these options must handle the/ route, since it is used when an invalid initialRoute is specified on startup (e.g. by another application launching this one with an intent on Android; see dart:ui.PlatformDispatcher.defaultRouteName).

This widget also configures the observer of the top-level Navigator (if any) to perform Hero animations.

The MaterialApp automatically creates a DefaultSelectionStyle. It uses the colors in the ThemeData.textSelectionTheme if they are not null; otherwise, the MaterialApp sets DefaultSelectionStyle.selectionColor toColorScheme.primary with 0.4 opacity andDefaultSelectionStyle.cursorColor to ColorScheme.primary.

If home, routes, onGenerateRoute, and onUnknownRoute are all null, and builder is not null, then no Navigator is created.

This example shows how to create a MaterialApp that disables the "debug" banner with a home route that will be displayed when the app is launched.

The MaterialApp displays a Scaffold

link

MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      title: const Text('Home'),
    ),
  ),
  debugShowCheckedModeBanner: false,
)

This example shows how to create a MaterialApp that uses the routes Map to define the "home" route and an "about" route.

link

MaterialApp(
  routes: <String, WidgetBuilder>{
    '/': (BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('Home Route'),
        ),
      );
    },
    '/about': (BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('About Route'),
        ),
      );
     }
   },
)

This example shows how to create a MaterialApp that defines a theme that will be used for material widgets in the app.

The MaterialApp displays a Scaffold with a dark background and a blue / grey AppBar at the top

link

MaterialApp(
  theme: ThemeData(
    brightness: Brightness.dark,
    primaryColor: Colors.blueGrey
  ),
  home: Scaffold(
    appBar: AppBar(
      title: const Text('MaterialApp Theme'),
    ),
  ),
)

Troubleshooting

Why is my app's text red with yellow underlines?

Text widgets that lack a Material ancestor will be rendered with an ugly red/yellow text style.

The typical fix is to give the widget a Scaffold ancestor. The Scaffold creates a Material widget that defines its default text style.

const MaterialApp(
  title: 'Material App',
  home: Scaffold(
    body: Center(
      child: Text('Hello World'),
    ),
  ),
)

See also:

Inheritance

Constructors

MaterialApp({Key? key, GlobalKey<NavigatorState>? navigatorKey, GlobalKey<ScaffoldMessengerState>? scaffoldMessengerKey, Widget? home, Map<String, WidgetBuilder> routes = const <String, WidgetBuilder>{}, String? initialRoute, RouteFactory? onGenerateRoute, InitialRouteListFactory? onGenerateInitialRoutes, RouteFactory? onUnknownRoute, NotificationListenerCallback<NavigationNotification>? onNavigationNotification, List<NavigatorObserver> navigatorObservers = const [], TransitionBuilder? builder, String? title = '', GenerateAppTitle? onGenerateTitle, Color? color, ThemeData? theme, ThemeData? darkTheme, ThemeData? highContrastTheme, ThemeData? highContrastDarkTheme, ThemeMode? themeMode = ThemeMode.system, Duration themeAnimationDuration = kThemeAnimationDuration, Curve themeAnimationCurve = Curves.linear, Locale? locale, Iterable<LocalizationsDelegate>? localizationsDelegates, LocaleListResolutionCallback? localeListResolutionCallback, LocaleResolutionCallback? localeResolutionCallback, Iterable<Locale> supportedLocales = const [Locale('en', 'US')], bool debugShowMaterialGrid = false, bool showPerformanceOverlay = false, bool checkerboardRasterCacheImages = false, bool checkerboardOffscreenLayers = false, bool showSemanticsDebugger = false, Map<ShortcutActivator, Intent>? shortcuts, Map<Type, Action<Intent>>? actions, String? restorationScopeId, ScrollBehavior? scrollBehavior, @Deprecated('Remove this parameter as it is now ignored. ' 'MaterialApp never introduces its own MediaQuery; the View widget takes care of that. ' 'This feature was deprecated after v3.7.0-29.0.pre.') bool useInheritedMediaQuery = false, AnimationStyle? themeAnimationStyle})

Creates a MaterialApp.

const

MaterialApp.router({Key? key, GlobalKey<ScaffoldMessengerState>? scaffoldMessengerKey, RouteInformationProvider? routeInformationProvider, RouteInformationParser<Object>? routeInformationParser, RouterDelegate<Object>? routerDelegate, RouterConfig<Object>? routerConfig, BackButtonDispatcher? backButtonDispatcher, TransitionBuilder? builder, String? title, GenerateAppTitle? onGenerateTitle, NotificationListenerCallback<NavigationNotification>? onNavigationNotification, Color? color, ThemeData? theme, ThemeData? darkTheme, ThemeData? highContrastTheme, ThemeData? highContrastDarkTheme, ThemeMode? themeMode = ThemeMode.system, Duration themeAnimationDuration = kThemeAnimationDuration, Curve themeAnimationCurve = Curves.linear, Locale? locale, Iterable<LocalizationsDelegate>? localizationsDelegates, LocaleListResolutionCallback? localeListResolutionCallback, LocaleResolutionCallback? localeResolutionCallback, Iterable<Locale> supportedLocales = const [Locale('en', 'US')], bool debugShowMaterialGrid = false, bool showPerformanceOverlay = false, bool checkerboardRasterCacheImages = false, bool checkerboardOffscreenLayers = false, bool showSemanticsDebugger = false, Map<ShortcutActivator, Intent>? shortcuts, Map<Type, Action<Intent>>? actions, String? restorationScopeId, ScrollBehavior? scrollBehavior, @Deprecated('Remove this parameter as it is now ignored. ' 'MaterialApp never introduces its own MediaQuery; the View widget takes care of that. ' 'This feature was deprecated after v3.7.0-29.0.pre.') bool useInheritedMediaQuery = false, AnimationStyle? themeAnimationStyle})

Creates a MaterialApp that uses the Router instead of a Navigator.

const

Properties

actionsMap<Type, Action<Intent>>?

The default map of intent keys to actions for the application.

final

backButtonDispatcherBackButtonDispatcher?

A delegate that decide whether to handle the Android back button intent.

final

builderTransitionBuilder?

A builder for inserting widgets above the Navigator or - when theWidgetsApp.router constructor is used - above the Router but below the other widgets created by the WidgetsApp widget, or for replacing theNavigator/Router entirely.

final

checkerboardOffscreenLayersbool

Turns on checkerboarding of layers rendered to offscreen bitmaps.

final

checkerboardRasterCacheImagesbool

Turns on checkerboarding of raster cache images.

final

colorColor?

The primary color to use for the application in the operating system interface.

final

darkThemeThemeData?

The ThemeData to use when a 'dark mode' is requested by the system.

final

Turns on a little "DEBUG" banner in debug mode to indicate that the app is in debug mode. This is on by default (in debug mode), to turn it off, set the constructor argument to false. In release mode this has no effect.

final

debugShowMaterialGridbool

Turns on a GridPaper overlay that paints a baseline grid Material apps.

final

hashCodeint

The hash code for this object.

no setterinherited

highContrastDarkThemeThemeData?

The ThemeData to use when a 'dark mode' and 'high contrast' is requested by the system.

final

highContrastThemeThemeData?

The ThemeData to use when 'high contrast' is requested by the system.

final

homeWidget?

The widget for the default route of the app (Navigator.defaultRouteName, which is /).

final

initialRouteString?

The name of the first route to show, if a Navigator is built.

final

keyKey?

Controls how one widget replaces another widget in the tree.

finalinherited

localeLocale?

The initial locale for this app's Localizations widget is based on this value.

final

localeListResolutionCallbackLocaleListResolutionCallback?

This callback is responsible for choosing the app's locale when the app is started, and when the user changes the device's locale.

final

localeResolutionCallbackLocaleResolutionCallback?

The signature of WidgetsApp.localeResolutionCallback.

final

localizationsDelegatesIterable<LocalizationsDelegate>?

The delegates for this app's Localizations widget.

final

navigatorKeyGlobalKey<NavigatorState>?

A key to use when building the Navigator.

final

navigatorObserversList<NavigatorObserver>?

The list of observers for the Navigator created for this app.

final

onGenerateInitialRoutesInitialRouteListFactory?

The routes generator callback used for generating initial routes ifinitialRoute is provided.

final

onGenerateRouteRouteFactory?

The route generator callback used when the app is navigated to a named route.

final

onGenerateTitleGenerateAppTitle?

If non-null this callback function is called to produce the app's title string, otherwise title is used.

final

onNavigationNotificationNotificationListenerCallback<NavigationNotification>?

The callback to use when receiving a NavigationNotification.

final

onUnknownRouteRouteFactory?

Called when onGenerateRoute fails to generate a route, except for theinitialRoute.

final

restorationScopeIdString?

The identifier to use for state restoration of this app.

final

routeInformationParserRouteInformationParser<Object>?

A delegate to parse the route information from therouteInformationProvider into a generic data type to be processed by the routerDelegate at a later stage.

final

routeInformationProviderRouteInformationProvider?

A object that provides route information through theRouteInformationProvider.value and notifies its listener when its value changes.

final

routerConfigRouterConfig<Object>?

An object to configure the underlying Router.

final

routerDelegateRouterDelegate<Object>?

A delegate that configures a widget, typically a Navigator, with parsed result from the routeInformationParser.

final

routesMap<String, WidgetBuilder>?

The application's top-level routing table.

final

runtimeTypeType

A representation of the runtime type of the object.

no setterinherited

scaffoldMessengerKeyGlobalKey<ScaffoldMessengerState>?

A key to use when building the ScaffoldMessenger.

final

scrollBehaviorScrollBehavior?

The default ScrollBehavior for the application.

final

shortcutsMap<ShortcutActivator, Intent>?

The default map of keyboard shortcuts to intents for the application.

final

showPerformanceOverlaybool

Turns on a performance overlay.

final

showSemanticsDebuggerbool

Turns on an overlay that shows the accessibility information reported by the framework.

final

supportedLocalesIterable<Locale>

The list of locales that this app has been localized for.

final

themeThemeData?

Default visual properties, like colors fonts and shapes, for this app's material widgets.

final

themeAnimationCurveCurve

The curve to apply when animating theme changes.

final

themeAnimationDurationDuration

The duration of animated theme changes.

final

themeAnimationStyleAnimationStyle?

Used to override the theme animation curve and duration.

final

themeModeThemeMode?

Determines which theme will be used by the application if both themeand darkTheme are provided.

final

titleString?

A one-line description used by the device to identify the app for the user.

final

useInheritedMediaQuerybool

Deprecated. This setting is now ignored.

final

Methods

createElement()→ StatefulElement

Creates a StatefulElement to manage this widget's location in the tree.

inherited

createState()→ State<MaterialApp>

Creates the mutable state for this widget at a given location in the tree.

override

debugDescribeChildren()→ List<DiagnosticsNode>

Returns a list of DiagnosticsNode objects describing this node's children.

inherited

debugFillProperties(DiagnosticPropertiesBuilder properties)→ void

Add additional properties associated with the node.

inherited

noSuchMethod(Invocation invocation)→ dynamic

Invoked when a nonexistent method or property is accessed.

inherited

toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style})→ DiagnosticsNode

Returns a debug representation of the object that is used by debugging tools and by DiagnosticsNode.toStringDeep.

inherited

toString({DiagnosticLevel minLevel = DiagnosticLevel.info})→ String

A string representation of this object.

inherited

toStringDeep({String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65})→ String

Returns a string representation of this node and its descendants.

inherited

toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug})→ String

Returns a one-line detailed description of the object.

inherited

toStringShort()→ String

A short, textual description of this widget.

inherited

Operators

operator ==(Object other)→ bool

The equality operator.

inherited

Static Methods

createMaterialHeroController()→ HeroController

The HeroController used for Material page transitions.