Skip to content

[go_router] Added onPushRoute; intercepts route pushes from the application host #3524

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/go_router/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 6.4.2
- Adds `onPushRoute` callback to **GoRouter** that can be used to intercept route pushes from the application host.

## 6.4.1
- Adds `initialExtra` to **GoRouter** to pass extra data alongside `initialRoute`.

Expand Down
1 change: 1 addition & 0 deletions packages/go_router/lib/go_router.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ library go_router;

export 'src/configuration.dart'
show GoRoute, GoRouterState, RouteBase, ShellRoute;
export 'src/information_provider.dart' show PushRouteDecision;
export 'src/misc/extensions.dart';
export 'src/misc/inherited_router.dart';
export 'src/pages/custom_transition_page.dart';
Expand Down
60 changes: 47 additions & 13 deletions packages/go_router/lib/src/information_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,46 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/foundation.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

/// The decision on how to handle the route
/// when host tells the application to push a new one.
enum PushRouteDecision {
/// Delegate the route information to [WidgetsBindingObserver.didPushRoute],
/// in registration order, until one returns true.
delegate,

/// Prevent the route information from being addressed by [GoRouter].
prevent,

/// Delegate the route information to the [GoRouter].
navigate,
}

/// Signature for callbacks that report a pushed route information.
typedef PushRouteCallback = FutureOr<PushRouteDecision> Function(
RouteInformation routeInformation,
);

/// The [RouteInformationProvider] created by go_router.
class GoRouteInformationProvider extends RouteInformationProvider
with WidgetsBindingObserver, ChangeNotifier {
/// Creates a [GoRouteInformationProvider].
GoRouteInformationProvider({
required RouteInformation initialRouteInformation,
PushRouteCallback? onPushRoute,
Listenable? refreshListenable,
}) : _refreshListenable = refreshListenable,
_onPushRoute = onPushRoute,
_value = initialRouteInformation {
_refreshListenable?.addListener(notifyListeners);
}

final Listenable? _refreshListenable;
final PushRouteCallback? _onPushRoute;

// ignore: unnecessary_non_null_assertion
static WidgetsBinding get _binding => WidgetsBinding.instance;
Expand Down Expand Up @@ -58,13 +81,27 @@ class GoRouteInformationProvider extends RouteInformationProvider
RouteInformation _valueInEngine =
RouteInformation(location: _binding.platformDispatcher.defaultRouteName);

void _platformReportsNewRouteInformation(RouteInformation routeInformation) {
if (_value == routeInformation) {
return;
Future<bool> _platformReportsNewRouteInformation(
RouteInformation routeInformation,
) async {
final PushRouteDecision decision =
await _onPushRoute?.call(routeInformation) ??
PushRouteDecision.navigate;

switch (decision) {
case PushRouteDecision.delegate:
return false;
case PushRouteDecision.prevent:
return true;
case PushRouteDecision.navigate:
assert(hasListeners);
if (_value != routeInformation) {
_value = routeInformation;
_valueInEngine = routeInformation;
notifyListeners();
}
return true;
}
_value = routeInformation;
_valueInEngine = routeInformation;
notifyListeners();
}

@override
Expand Down Expand Up @@ -94,15 +131,12 @@ class GoRouteInformationProvider extends RouteInformationProvider

@override
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
assert(hasListeners);
_platformReportsNewRouteInformation(routeInformation);
return SynchronousFuture<bool>(true);
return _platformReportsNewRouteInformation(routeInformation);
}

@override
Future<bool> didPushRoute(String route) {
assert(hasListeners);
_platformReportsNewRouteInformation(RouteInformation(location: route));
return SynchronousFuture<bool>(true);
final RouteInformation routeInformation = RouteInformation(location: route);
return _platformReportsNewRouteInformation(routeInformation);
}
}
2 changes: 2 additions & 0 deletions packages/go_router/lib/src/router.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ class GoRouter extends ChangeNotifier implements RouterConfig<RouteMatchList> {
bool debugLogDiagnostics = false,
GlobalKey<NavigatorState>? navigatorKey,
String? restorationScopeId,
PushRouteCallback? onPushRoute,
}) : backButtonDispatcher = RootBackButtonDispatcher(),
assert(
initialExtra == null || initialLocation != null,
Expand Down Expand Up @@ -91,6 +92,7 @@ class GoRouter extends ChangeNotifier implements RouterConfig<RouteMatchList> {
location: _effectiveInitialLocation(initialLocation),
state: initialExtra,
),
onPushRoute: onPushRoute,
refreshListenable: refreshListenable,
);

Expand Down
2 changes: 1 addition & 1 deletion packages/go_router/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: go_router
description: A declarative router for Flutter based on Navigation 2 supporting
deep linking, data-driven routes and more
version: 6.4.1
version: 6.4.2
repository: https://github.com/flutter/packages/tree/main/packages/go_router
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+go_router%22

Expand Down
112 changes: 112 additions & 0 deletions packages/go_router/test/go_router_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3380,6 +3380,118 @@ void main() {
},
);
});

group('push route decision', () {
testWidgets(
'defaults to "navigate"',
(WidgetTester tester) async {
final List<RouteBase> routes = <RouteBase>[
GoRoute(
path: '/',
builder: (_, __) => const SizedBox(),
),
GoRoute(
path: '/dummy',
builder: (_, __) => const _DidPushRouteWidget(),
),
];

final GoRouter router = await createRouter(routes, tester);

sendPlatformUrl('/dummy');
await tester.pumpAndSettle();

expect(router.location, '/dummy');
expect(find.text('DidPushRoute: null'), findsOneWidget);
},
);

testWidgets(
'based on location',
(WidgetTester tester) async {
final List<RouteBase> routes = <RouteBase>[
GoRoute(
path: '/',
builder: (_, __) => const _DidPushRouteWidget(),
),
GoRoute(
path: '/dummy',
builder: (_, __) => const _DidPushRouteWidget(),
),
];

final GoRouter router = await createRouter(
routes,
tester,
onPushRoute: (RouteInformation routeInformation) {
final String? location = routeInformation.location;

switch (location) {
case '/prevent':
return PushRouteDecision.prevent;
case '/delegate':
return PushRouteDecision.delegate;
}

return PushRouteDecision.navigate;
},
);

sendPlatformUrl('/dummy');
await tester.pumpAndSettle();
expect(router.location, '/dummy');
expect(find.text('DidPushRoute: null'), findsOneWidget);

sendPlatformUrl('/prevent');
await tester.pumpAndSettle();
expect(router.location, '/dummy');
expect(find.text('DidPushRoute: null'), findsOneWidget);

sendPlatformUrl('/delegate');
await tester.pumpAndSettle();
expect(router.location, '/dummy');
expect(find.text('DidPushRoute: /delegate'), findsOneWidget);
},
);
});
}

class _DidPushRouteWidget extends StatefulWidget {
const _DidPushRouteWidget();

@override
State<_DidPushRouteWidget> createState() => _DidPushRouteWidgetState();
}

class _DidPushRouteWidgetState extends State<_DidPushRouteWidget>
with WidgetsBindingObserver {
String? _route;

@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}

@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}

@override
Future<bool> didPushRoute(String route) {
if (mounted) {
_route = route;
setState(() {});
}
return SynchronousFuture<bool>(true);
}

@override
Widget build(BuildContext context) {
return Text('DidPushRoute: $_route');
}
}

/// This allows a value of type T or T? to be treated as a value of type T?.
Expand Down
40 changes: 36 additions & 4 deletions packages/go_router/test/information_provider_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,50 @@ void main() {
group('GoRouteInformationProvider', () {
testWidgets('notifies its listeners when set by the app',
(WidgetTester tester) async {
late final GoRouteInformationProvider provider =
GoRouteInformationProvider(initialRouteInformation: initialRoute);
final GoRouteInformationProvider provider = GoRouteInformationProvider(
initialRouteInformation: initialRoute,
);
provider.addListener(expectAsync0(() {}));
provider.value = newRoute;
});

testWidgets('notifies its listeners when set by the platform',
(WidgetTester tester) async {
late final GoRouteInformationProvider provider =
GoRouteInformationProvider(initialRouteInformation: initialRoute);
final GoRouteInformationProvider provider = GoRouteInformationProvider(
initialRouteInformation: initialRoute,
);
provider.addListener(expectAsync0(() {}));
provider.didPushRouteInformation(newRoute);
});

group('[push route decision]', () {
test('didPushRoute is false for "delegate"', () async {
final GoRouteInformationProvider provider = GoRouteInformationProvider(
initialRouteInformation: initialRoute,
onPushRoute: (_) => PushRouteDecision.delegate,
);
expect(await provider.didPushRoute('/new'), isFalse);
expect(await provider.didPushRouteInformation(newRoute), isFalse);
});

test('didPushRoute is true for "prevent"', () async {
final GoRouteInformationProvider provider = GoRouteInformationProvider(
initialRouteInformation: initialRoute,
onPushRoute: (_) => PushRouteDecision.prevent,
);
expect(await provider.didPushRoute('/new'), isTrue);
expect(await provider.didPushRouteInformation(newRoute), isTrue);
});

test('didPushRoute is true for "navigate"', () async {
final GoRouteInformationProvider provider = GoRouteInformationProvider(
initialRouteInformation: initialRoute,
onPushRoute: (_) => PushRouteDecision.navigate,
);
provider.addListener(expectAsync0(() {}));
expect(await provider.didPushRoute('/new'), isTrue);
expect(await provider.didPushRouteInformation(newRoute), isTrue);
});
});
});
}
3 changes: 3 additions & 0 deletions packages/go_router/test/test_helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'package:go_router/src/information_provider.dart';

Future<GoRouter> createGoRouter(WidgetTester tester) async {
final GoRouter goRouter = GoRouter(
Expand Down Expand Up @@ -145,6 +146,7 @@ Future<GoRouter> createRouter(
int redirectLimit = 5,
GlobalKey<NavigatorState>? navigatorKey,
GoRouterWidgetBuilder? errorBuilder,
PushRouteCallback? onPushRoute,
}) async {
final GoRouter goRouter = GoRouter(
routes: routes,
Expand All @@ -156,6 +158,7 @@ Future<GoRouter> createRouter(
(BuildContext context, GoRouterState state) =>
TestErrorScreen(state.error!),
navigatorKey: navigatorKey,
onPushRoute: onPushRoute,
);
await tester.pumpWidget(
MaterialApp.router(
Expand Down