🧭

[Flutter] onGenerateRoute 画面遷移を1つのファイルで管理する

2022/09/21に公開

はじめに

各ページ毎にNavigator.pushで画面遷移を実装すると冗長になってしまいがちなので、
「onGenerateRoute」を用いて画面遷移を管理しやすくしようと思います。

サンプルコード

app.dart:「onGenerateRoute」を指定
home.dart:始めのページ
hoge.dart:遷移先のページ
route.dart:画面遷移を管理

app.dart
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      onGenerateRoute: RouteGenerator.generateRoute, //route.dartに依存
      home: Home(),
    );
  }
}
home.dart
class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('HOME')),
      body: Center(
        child: TextButton(
          child: Text('hogeへ'),
          onPressed: () {
            // 遷移先のページを指定
            Navigator.pushNamed(context, '/hoge');
          },
        ),
      ),
    );
  }
}
hoge.dart
class Hoge extends StatelessWidget {
  const Hoge({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('hoge')),
      body: Center(child: Text('hoge')),
    );
  }
}
route.dart
class RouteGenerator {
  // 各ページを定義
  static const String home = '/';
  static const String hoge = '/hoge';

  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case home:
        return MaterialPageRoute(
          builder: (_) => Home(),
        );
      case hoge:
        return MaterialPageRoute(
          // 遷移先のページを定指定
          builder: (_) => Hoge(),
          fullscreenDialog: true,
        );
      default:
        // 非該当時のエラー
        throw Exception('Route not found');
    }
  }
}

動作確認

おわりに

遷移時のアニメーション指定だけ実装したかったのでこれで充分でしたが、
他により良いroute管理があれば随時記事を更新していこうと思います。

Discussion