Skip to content

[go_router] add missing go/push control to redirect function #116164

Closed

Description

@hunterwilhelm

TLDR

Add a way to control the redirect behavior to force popUntil, push, or go for authentication flows.

The Problem

The redirect function is confusing to use. For example, when the page redirects to a page that already exists on the navigation stack, it will perform popUntil. Most of the time though, it replaces the current page with the redirected page.

Use Cases

Using redirect for protecting routes if the use is not authenticated or not authorized.

  • When a user logs out, the redirect should be able to use go to clear the stack.

Using redirect for protecting routes if the use is authenticated or authorized.

  • When a user logs in, the redirect should be able to use go to clear the stack.
  • Pushing to a new route instead of going/popUntiling

Discussions

Demonstration

Here is an example of the weirdness of the redirect function.

  1. Press Go to details with push
  2. Press Go to home with push as many times as you want to build up the stack
  3. Press go to home with auth state and it performs a popUntil ⚠️ I expected a push!
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'dart:async';

void main() => runApp(const MyApp());

class RouterNotifier extends ChangeNotifier {
  late final StreamSubscription<bool> _stream;
  bool? authState;
  RouterNotifier(AuthService authService) {
    _stream = authService.authStateChanges.listen((event) {
      authState = event;
      notifyListeners();
    });
  }

  String? redirect(BuildContext context, GoRouterState state) {
    final onHomePage = state.location == '/';
    final isSignedIn = authState == true;
    if (isSignedIn && onHomePage) {
      return '/details';
    }
    if (!isSignedIn && !onHomePage) {
      return '/';
    }
    return null;
  }

  @override
  void dispose() {
    super.dispose();
    _stream.cancel();
  }
}

final _mockState = StreamController<bool>();

class AuthService {
  Stream<bool> get authStateChanges => _mockState.stream;
  void signIn() {
    _mockState.add(true);
  }

  void signOut() {
    _mockState.add(false);
  }
}

class AppRouter {
  final authService = AuthService();

  GoRouter get router {
    final routerNotifier = RouterNotifier(authService);
    return GoRouter(
      refreshListenable: routerNotifier,
      redirect: routerNotifier.redirect,
      initialLocation: '/details',
      routes: <RouteBase>[
        GoRoute(
          path: '/',
          builder: (BuildContext context, GoRouterState state) {
            return const HomeScreen();
          },
          routes: <RouteBase>[
            GoRoute(
              path: 'details',
              builder: (BuildContext context, GoRouterState state) {
                return const DetailsScreen();
              },
            ),
          ],
        ),
      ],
    );
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final appRouter = AppRouter();
    return MaterialApp.router(
      routerConfig: appRouter.router,
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () {
                AuthService().signIn();
              },
              child: const Text('Go to details with auth state'),
            ),
          ],
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Details Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => context.push('/'),
              child: const Text('Go to home with push'),
            ),
            Container(height: 100),
            ElevatedButton(
              onPressed: () {
                AuthService().signOut();
              },
              child: const Text('Go to home with auth state'),
            ),
          ],
        ),
      ),
    );
  }
}

Activity

  1. added
    in triage
    on Nov 29, 2022
  2. huycozy commented on Nov 29, 2022

    @huycozy
    Member

    Hi @hunterwilhelm, please check if this issue is similar to #114131.

  3. added
    waiting for response
    on Nov 29, 2022
  4. hunterwilhelm commented on Nov 29, 2022

    @hunterwilhelm
    Author

    @huycozy Yes, this is a duplicate.

  5. removed
    waiting for response
    on Nov 29, 2022
  6. added
    r: duplicate
    and removed
    in triage
    on Nov 30, 2022
  7. github-actions commented on Mar 5, 2023

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  8. locked as resolved and limited conversation to collaborators on Mar 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    r: duplicate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions