From 34f0be6d9a4c4077f3f732db81a043791e1b24a4 Mon Sep 17 00:00:00 2001 From: NBA2K1 <78034913+NBA2K1@users.noreply.github.com> Date: Sat, 31 May 2025 17:43:59 +0200 Subject: [PATCH] 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.) ``` --- lib/router/router.dart | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/lib/router/router.dart b/lib/router/router.dart index 184ba3e5..b51cef65 100644 --- a/lib/router/router.dart +++ b/lib/router/router.dart @@ -68,21 +68,32 @@ GoRouter router(Ref ref) { @riverpod class RouterCurrentLocationState extends _$RouterCurrentLocationState { + bool _didSubscribe = false; @override String? build(BuildContext context) { - _listener(); + // Delay listener‐registration 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(); + }); }); } }