<aside> 💡 GoRoutuer가 제공해주는 가장 유용한 기능

</aside>

login_screen.dart

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:go_router_v7_actual/layout/default_layout.dart';
import 'package:go_router_v7_actual/route/router.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  @override
  Widget build(BuildContext context) {
    return DefaultLayout(
      body: ListView(
        children: [
          Text('Login State : $authState'),
          ElevatedButton(
            onPressed: () {
              setState(() {
                authState = !authState;
              });
            },
            child: Text(
              authState ? 'logout' : 'login',
            ),
          ),
          ElevatedButton(
            onPressed: () {
              if(GoRouterState.of(context).location == '/login'){
                context.go('/login/private');
              }else{
                context.go('/login2/private');
              }
            },
            child: Text(
              'Go to Private Route',
            ),
          ),
        ],
      ),
    );
  }
}

private_screen.dart

import 'package:flutter/material.dart';
import 'package:go_router_v7_actual/layout/default_layout.dart';

class PrivateScreen extends StatelessWidget {
  const PrivateScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DefaultLayout(
      body: Center(
        child: Text('Private Screen'),
      ),
    );
  }
}

router.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;
  },