Update router.dart

Fix exception when using "Select Widget Mode" of the Flutter Inspector:

```
Exception has occurred.
FlutterError (Tried to modify a provider while the widget tree was building.
If you are encountering this error, chances are you tried to modify a provider
in a widget life-cycle, such as but not limited to:
- build
- initState
- dispose
- didUpdateWidget
- didChangeDependencies

Modifying a provider inside those life-cycles is not allowed, as it could
lead to an inconsistent UI state. For example, two widgets could listen to the
same provider, but incorrectly receive different states.

To fix this problem, you have one of two solutions:
- (preferred) Move the logic for modifying your provider outside of a widget
  life-cycle. For example, maybe you could update your provider inside a button's
  onPressed instead.

- Delay your modification, such as by encapsulating the modification
  in a `Future(() {...})`.
  This will perform your update after the widget tree is done building.)
```
This commit is contained in:
NBA2K1 2025-05-31 17:43:59 +02:00
parent 2ba453a394
commit 34f0be6d9a

View file

@ -68,21 +68,32 @@ GoRouter router(Ref ref) {
@riverpod
class RouterCurrentLocationState extends _$RouterCurrentLocationState {
bool _didSubscribe = false;
@override
String? build(BuildContext context) {
_listener();
// Delay listenerregistration until after the first frame.
if (!_didSubscribe) {
_didSubscribe = true;
// Schedule the registration to run after the first build/frame:
WidgetsBinding.instance.addPostFrameCallback((_) {
_listener();
});
}
return null;
}
_listener() {
final router = GoRouter.of(context);
void _listener() {
final router = ref.read(routerProvider);
router.routerDelegate.addListener(() {
final RouteMatch lastMatch =
router.routerDelegate.currentConfiguration.last;
final RouteMatchList matchList = lastMatch is ImperativeRouteMatch
? lastMatch.matches
: router.routerDelegate.currentConfiguration;
state = matchList.uri.toString();
WidgetsBinding.instance.addPostFrameCallback((_) {
final RouteMatchList matches =
router.routerDelegate.currentConfiguration;
final RouteMatch lastMatch = matches.last;
final RouteMatchList matchList = lastMatch is ImperativeRouteMatch
? lastMatch.matches
: matches;
state = matchList.uri.toString();
});
});
}
}