정의 한적 없는 GoRouter로 이동했을떄 보여주는 화면

router.dart

errorBuilder: (context, state) => ErrorScreen(
    error: state.error.toString(),
  ),
  debugLogDiagnostics: true,
);

맨 마지막 부분에 추가해준다.

전체 코드

import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';
import 'package:go_router_v7_actual/screens/10_transition_screen_1.dart';
import 'package:go_router_v7_actual/screens/10_transition_screen_2.dart';
import 'package:go_router_v7_actual/screens/11_error_screen.dart';
import 'package:go_router_v7_actual/screens/1_basic_screen.dart';
import 'package:go_router_v7_actual/screens/3_push_screen.dart';
import 'package:go_router_v7_actual/screens/4_pop_base_screen.dart';
import 'package:go_router_v7_actual/screens/5_pop_return_screen.dart';
import 'package:go_router_v7_actual/screens/6_path_param_screen.dart';
import 'package:go_router_v7_actual/screens/7_query_parameter.dart';
import 'package:go_router_v7_actual/screens/8_nested_child_screen.dart';
import 'package:go_router_v7_actual/screens/8_nested_screen.dart';
import 'package:go_router_v7_actual/screens/9_login_screen.dart';
import 'package:go_router_v7_actual/screens/9_private_screen.dart';
import 'package:go_router_v7_actual/screens/root_screen.dart';

// 로그인이 됐는지 안됐는지
// true - login OK / false - login NO
bool authState = false;

// <https://blog.codefactory.ai/> -> / -> path
// <https://blog.codefactory.ai/flutter> -> /flutter
// / -> home
// /basic -> basic screen
// /basic/named ->
// /named
final router = GoRouter(
  redirect: (context, state) {
    // return string (path) -> 해당 라우트로 이동한다 (path)
    // return null -> 원래 이동하려던 라우트로 이동한다.
    if (state.location == '/login/private' && !authState) {
      return '/login';
    }

    return null;
  },
  routes: [
    GoRoute(
     ...
  ],
  errorBuilder: (context, state) => ErrorScreen(
    error: state.error.toString(),
  ),
  debugLogDiagnostics: true,
);

debugLogDiagnostics: true 는 어떤 라우터들이 등록됐는지 터미널에서 볼 수 있고

이동할때마다 GoRouter 로그가 나온다.

error_screen.dart

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

class ErrorScreen extends StatelessWidget {
  final String error;

  const ErrorScreen({
    required this.error,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('에러'),
      ),
      body: ListView(
        children: [
          Text('Error: $error'),
          ElevatedButton(
            onPressed: () {
              context.go('/');
            },
            child: Text(
              '홈으로',
            ),
          ),
        ],
      ),
    );
  }
}

에러가 발생했을 떄 이 화면으로 이동하는 로직임