Skip to content

[go_router_builder] Add support for relative routes #7174

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
wants to merge 14 commits into from
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
4 changes: 4 additions & 0 deletions packages/go_router/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 14.2.1
- Allows going to a path relatively by prefixing `./`
- Adds `TypedRelativeGoRoute`

## 14.2.0

- Added proper `redirect` handling for `ShellRoute.$route` and `StatefulShellRoute.$route` for proper redirection handling in case of code generation.
Expand Down
120 changes: 120 additions & 0 deletions packages/go_router/example/lib/go_relative.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

/// This sample app demonstrates how to use go relatively with GoRouter.go('./$path').
void main() => runApp(const MyApp());

/// The route configuration.
final GoRouter _router = GoRouter(
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();
},
routes: <RouteBase>[
GoRoute(
path: 'settings',
builder: (BuildContext context, GoRouterState state) {
return const SettingsScreen();
},
),
],
),
],
),
],
);

/// The main app.
class MyApp extends StatelessWidget {
/// Constructs a [MyApp]
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
);
}
}

/// The home screen
class HomeScreen extends StatelessWidget {
/// Constructs a [HomeScreen]
const HomeScreen({super.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: () => context.go('./details'),
child: const Text('Go to the Details screen'),
),
],
),
),
);
}
}

/// The details screen
class DetailsScreen extends StatelessWidget {
/// Constructs a [DetailsScreen]
const DetailsScreen({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details Screen')),
body: Center(
child: Column(
children: <Widget>[
TextButton(
onPressed: () {
context.pop();
},
child: const Text('go back'),
),
TextButton(
onPressed: () {
context.go('./settings');
},
child: const Text('Go to the Settings screen'),
),
],
)),
);
}
}

/// The settings screen
class SettingsScreen extends StatelessWidget {
/// Constructs a [SettingsScreen]
const SettingsScreen({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings Screen')),
body: const Center(
child: Text('Settings'),
),
);
}
}
21 changes: 21 additions & 0 deletions packages/go_router/example/test/go_relative_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter_test/flutter_test.dart';
import 'package:go_router_examples/go_relative.dart' as example;

void main() {
testWidgets('example works', (WidgetTester tester) async {
await tester.pumpWidget(const example.MyApp());
expect(find.byType(example.HomeScreen), findsOneWidget);

await tester.tap(find.text('Go to the Details screen'));
await tester.pumpAndSettle();
expect(find.byType(example.DetailsScreen), findsOneWidget);

await tester.tap(find.text('Go to the Settings screen'));
await tester.pumpAndSettle();
expect(find.byType(example.SettingsScreen), findsOneWidget);
});
}
10 changes: 8 additions & 2 deletions packages/go_router/lib/src/information_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import 'match.dart';
import 'path_utils.dart';

/// The type of the navigation.
///
Expand Down Expand Up @@ -135,11 +136,16 @@ class GoRouteInformationProvider extends RouteInformationProvider
}

void _setValue(String location, Object state) {
final Uri uri = Uri.parse(location);
Uri uri = Uri.parse(location);

// Check for relative location
if (location.startsWith('./')) {
uri = concatenateUris(_value.uri, uri);
}

final bool shouldNotify =
_valueHasChanged(newLocationUri: uri, newState: state);
_value = RouteInformation(uri: Uri.parse(location), state: state);
_value = RouteInformation(uri: uri, state: state);
if (shouldNotify) {
notifyListeners();
}
Expand Down
14 changes: 14 additions & 0 deletions packages/go_router/lib/src/path_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,20 @@ String concatenatePaths(String parentPath, String childPath) {
return '${parentPath == '/' ? '' : parentPath}/$childPath';
}

/// Concatenates two Uri. It will [concatenatePaths] the parent's and the child's paths, and take only the child's parameters.
///
/// e.g: pathA = /a?fid=f1, pathB = c/d?pid=p2, concatenatePaths(pathA, pathB) = /a/c/d?pid=2.
Uri concatenateUris(Uri parentUri, Uri childUri) {
Uri newUri = parentUri.replace(
path: concatenatePaths(parentUri.path, childUri.path),
queryParameters: childUri.queryParameters,
);

// Parse the new normalized uri to remove unnecessary parts, like the trailing '?'.
newUri = Uri.parse(canonicalUri(newUri.toString()));
return newUri;
}

/// Normalizes the location string.
String canonicalUri(String loc) {
if (loc.isEmpty) {
Expand Down
22 changes: 22 additions & 0 deletions packages/go_router/lib/src/route_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,28 @@ class TypedGoRoute<T extends GoRouteData> extends TypedRoute<T> {
final List<TypedRoute<RouteData>> routes;
}

/// A superclass for each typed go route descendant
@Target(<TargetKind>{TargetKind.library, TargetKind.classType})
class TypedRelativeGoRoute<T extends GoRouteData> extends TypedRoute<T> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't see the difference between this and TypedGoRoute it seems to me that if user uses go_router_builder they are not using url string to navigate so they don't really need relative routing?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well they won't be using './$path' directly, but they'll use route.goRelative(), which uses that under the hood.

Not sure if I got your question right thou..

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant they could define a TypedGoRoute directly and do GoRouteData.go, why would they want to define a TypedRelativeRoute ?

Copy link

@thangmoxielabs thangmoxielabs Aug 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They can't define TypedGoRoute in multiple places. Take the example in the description, the relativeRoute was declared in a variable and passed in 2 routes. Had that been normal TypedGoRoute, it would've produced 2 extensions with the same name, of which locations are different, and results in build time error

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be two different feature right?

  1. is to be able to do go('./relative')
  2. is to be able to reuse the same RouteData with same relative path in different sub route.

and 2 needs to build on top of 1.
If so I think we should separate the 2 into a new pr to make review simpler.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh looks like you already did #6825.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

okay... so do I need to change anything else?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest removing the TypeRelativeRoute from #6825 and do all the TypeRelativeRoute thing in a separate pr

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TypedRelativeRoute needs to be landed in order for this PR to work. The reason this PR is working right now is because of the dependency_overrides, which I meant to remove after the #6825 is merged. Can you suggest how do I remove the TypedRelativeRoute? Do I create a PR with only TypedRelativeRoute declaration, wait for it to get merged and then continue with this PR?

Imo it's feels weird to me that an annotation of a builder package belongs to the main package and not in the builder package, but maybe there is a technical reason for that that I don't know

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No I meant the TypedRelativeRoute should be separate from #6825 since they are not related. and then we can review and merge #6825 first before we review TypedRelativeRoute separately.

/// Default const constructor
const TypedRelativeGoRoute({
required this.path,
this.routes = const <TypedRoute<RouteData>>[],
});

/// The relative path that corresponds to this route.
///
/// See [GoRoute.path].
///
///
final String path;

/// Child route definitions.
///
/// See [RouteBase.routes].
final List<TypedRoute<RouteData>> routes;
}

/// A superclass for each typed shell route descendant
@Target(<TargetKind>{TargetKind.library, TargetKind.classType})
class TypedShellRoute<T extends ShellRouteData> extends TypedRoute<T> {
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: 14.2.0
version: 14.2.1
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
Loading