Skip to content

Instantly share code, notes, and snippets.

@jackd
Last active September 4, 2024 11:04
Show Gist options
  • Select an option

  • Save jackd/ee1702fd06d189fe31c71bae355d736e to your computer and use it in GitHub Desktop.

Select an option

Save jackd/ee1702fd06d189fe31c71bae355d736e to your computer and use it in GitHub Desktop.
Demo of go_router interface inconsistency between GoRoute build and errorBuilder environments

This gist demonstrates a difference in behaviour of GoRouteState.of when instantiated in a child constructed via a GoRoute builder method compared to errorBuilder, despite both GoRouteStates having meaning / being in the function arguments.

Check it out here.

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const SimpleApp());
}
class SimpleApp extends StatelessWidget {
const SimpleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: GoRouter(routes: [
GoRoute(path: '/', builder: (context, state) => RouteExplorer(state))
], errorBuilder: (context, state) => RouteExplorer(state)));
}
}
class RouteExplorer extends StatelessWidget {
final GoRouterState state;
const RouteExplorer(this.state, {super.key});
@override
Widget build(BuildContext context) {
GoRouterState? fetchedState;
try {
fetchedState = GoRouterState.of(context);
} catch (_) {}
return Scaffold(
body: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
...[
state,
fetchedState
].map((s) => Text(s == null ? 'Null state' : 'uri.path = ${s.uri.path}')),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: ['/', '/foo']
.map((path) => ElevatedButton(
onPressed: () => context.go(path), child: Text(path)))
.toList())
]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment