あぼぼーぼ・ぼーぼぼ

のんびり生きたい

Flutter for Webで404ページを表示させる

MaterialAppのonGenerateRouteプロパティを使うとURL直打ちでも指定のページを表示させられる。同様に未定義のURLが指定された場合に呼ばれるonUnknownRouteを使えばOK。

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      onGenerateRoute: (settings) {
        switch (settings.name) {
          case '/':
            return MaterialPageRoute(
              builder: (context) => MyHomePage(),
            );
        }
      },
      initialRoute: '/',
      onUnknownRoute: (RouteSettings settings) {
        return MaterialPageRoute(
          builder: (context) => MyNotFoundPage(),
        );
      },
    );
  }
}

ルーティングの処理順序はこのへんを参照。

# flutter/lib/src/material/app.dart#L57
/// 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.