アプリ開発・ゲーム開発のための勉強ブログ

FlutterとUnrealEngineの勉強をしています。

【Flutter】GoRouterでのエラー処理

認識されないURLを開こうとする等エラーを出した場合に、エラーページのスクリーンウィジェットに飛ばす処理を行う。

 

errorBuilder:

GoRouterの中でerrorBuilderを指定してエラー処理を行うスクリーンに画面遷移させる

GoRouter(
  /* ... */
  errorBuilder: (context, state) => ErrorScreen(state.error),
);


【実装】

  1. errorBuilder: (context, state) => const NotFoundScreen(),

↓のページに飛ばす

 

  1. class NotFoundScreen extends StatelessWidget {
  2.   const NotFoundScreen({super.key});
  3.  
  4.   @override
  5.   Widget build(BuildContext context) {
  6.     return Scaffold(
  7.       appBar: AppBar(),
  8.       body: Center(
  9.         child: Column(
  10.           children: [
  11.             const Text('404 - Page not found'),
  12.             TextButton(
  13.                 onPressed: () => context.goNamed(AppRoute.home.name),
  14.                 child: const Text("Go Home")),
  15.           ],
  16.         ),
  17.       ),
  18.     );
  19.   }
  20. }