Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested Navigation leads to crash when using Guards #486

Closed
svsk417 opened this issue Mar 6, 2022 · 1 comment · Fixed by #490
Closed

Nested Navigation leads to crash when using Guards #486

svsk417 opened this issue Mar 6, 2022 · 1 comment · Fixed by #490

Comments

@svsk417
Copy link

svsk417 commented Mar 6, 2022

Hi! Thanks for the good work! I found an issue with Guards and nested navigation. If you have any questions or need more info just give me a heads up. :)

Describe the bug
If using nested navigation like in the following example application, the app crashes, because the subtree containing the guard is removed from the tree (the context is disfunct) and therefore cannot resolve inherited widgets from the tree any more. This happens most probably because the context is cached within the beamer_delegate.dart line 716.

Beamer version:
master

To Reproduce
Execute the following example (wait for 30 seconds) using the following dependencies:

dependencies:
  flutter:
    sdk: flutter
  beamer:
    git:
      url: https://github.com/slovnicki/beamer.git
      path: package
  flutter_bloc: ^8.0.1

Application

import 'dart:async';

import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

void main() {
  runApp(MyApp());
}

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

  final routerDelegate = BeamerDelegate(
    initialPath: '/home',
    notFoundRedirectNamed: '/home',
    locationBuilder: RoutesLocationBuilder(
      routes: {
        '*': (context, state, data) => MainLocation(),
      },
    ),
  );

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => AuthenticationBloc(),
      child: MaterialApp.router(
          routeInformationParser: BeamerParser(),
          routerDelegate: routerDelegate,
          backButtonDispatcher:
              BeamerBackButtonDispatcher(delegate: routerDelegate)),
    );
  }
}

class MainLocation extends StatelessWidget {
  final routerDelegate = BeamerDelegate(
      guards: [
        BeamGuard(
            pathPatterns: ['/login'],
            guardNonMatching: true,
            check: (context, state) =>
                context.read<AuthenticationBloc>().state is AuthenticatedState,
            beamToNamed: (origin, target) => '/login')
      ],
      clearBeamingHistoryOn: {
        '/login'
      },
      locationBuilder: RoutesLocationBuilder(routes: {
        '/home': (context, state, data) =>
            SomePage(key: const ValueKey('home'), text: 'Home'),
        '/login': (context, state, data) =>
            SomePage(key: const ValueKey('login'), text: 'Login')
      }));

  MainLocation({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocListener<AuthenticationBloc, AuthenticationState>(
      listener: (context, state) {
        if (state is AuthenticatedState) {
          context.beamToNamed('/home');
        } else {
          context.beamToNamed('/login');
        }
      },
      child: Beamer(routerDelegate: routerDelegate),
    );
  }
}

class SomePage extends StatelessWidget {
  final String text;

  SomePage({Key? key, required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Center(child: Text(text)));
  }
}

@immutable
abstract class AuthenticationEvent {}

class AuthenticatedEvent extends AuthenticationEvent {}

class UnauthenticatedEvent extends AuthenticationEvent {}

@immutable
abstract class AuthenticationState {}

class AuthenticatedState extends AuthenticationState {}

class UnauthenticatedState extends AuthenticationState {}

class AuthenticationBloc
    extends Bloc<AuthenticationEvent, AuthenticationState> {
  final StreamController<bool> _isAuthenticatedStreamController =
      StreamController<bool>.broadcast();

  bool _isUserAuthenticated = true;
  bool get isUserAuthenticated => _isUserAuthenticated;

  AuthenticationBloc() : super(AuthenticatedState()) {
    Timer.periodic(const Duration(seconds: 10), (timer) {
      _isUserAuthenticated = !_isUserAuthenticated;
      if (_isUserAuthenticated) {
        add(AuthenticatedEvent());
      } else {
        add(UnauthenticatedEvent());
      }
    });
    on<AuthenticatedEvent>((event, emit) {
      emit(AuthenticatedState());
    });

    on<UnauthenticatedEvent>((event, emit) {
      emit(UnauthenticatedState());
    });
  }
}

Expected behavior
The new context, that is not disfunct, is used and the app does not crash.

OS

  • OS: Android Emulator Pixel 5 API Level 31
@slovnicki
Copy link
Owner

Hey @svsk417 👋
Thanks for creating an issue and providing a PR with the fix! 💪 💙

I will leave my comments in the PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants