Skip to content

[go_router] ShellRoute with CupertinoTabScaffold crashes with "multiple widgets used the same GlobalKey" #113757

Open

Description

@emirhanaydin

go_router version: 5.1.1

Steps to Reproduce

  1. Execute flutter run on the code sample
  2. Tap on a tab button and see FlutterError: "Multiple widgets used the same GlobalKey."

Expected results:
It should change tabs without crashing, as in the ShellRoute sample app.
The only difference is that the code sample below uses CupertinoTabScaffold and CupertinoTabBar instead of Material ones.

Actual results:
It crashes with the following exception:

Multiple widgets used the same GlobalKey.
The key [LabeledGlobalKey<NavigatorState>#c3094 shell] was used by multiple widgets. The parents of those widgets were different widgets that both had the following description:
  Builder
A GlobalKey can only be specified on one widget at a time in the widget tree.
Code sample
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

final GlobalKey<NavigatorState> _rootNavigatorKey =
    GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> _shellNavigatorKey =
    GlobalKey<NavigatorState>(debugLabel: 'shell');

void main() {
  runApp(ShellRouteCupertinoApp());
}

class ShellRouteCupertinoApp extends StatelessWidget {
  ShellRouteCupertinoApp({Key? key}) : super(key: key);

  final GoRouter _router = GoRouter(
    navigatorKey: _rootNavigatorKey,
    initialLocation: "/a",
    routes: <RouteBase>[
      ShellRoute(
        navigatorKey: _shellNavigatorKey,
        builder: (BuildContext context, GoRouterState state, Widget child) {
          return ScaffoldWithNavBar(child: child);
        },
        routes: <RouteBase>[
          /// The first screen to display in the bottom navigation bar.
          GoRoute(
            path: '/a',
            builder: (BuildContext context, GoRouterState state) {
              return const ScreenA();
            },
            routes: <RouteBase>[
              // The details screen to display stacked on the inner Navigator.
              // This will cover screen A but not the application shell.
              GoRoute(
                path: 'details',
                builder: (BuildContext context, GoRouterState state) {
                  return const DetailsScreen(label: 'A');
                },
              ),
            ],
          ),

          /// Displayed when the second item in the the bottom navigation bar is
          /// selected.
          GoRoute(
            path: '/b',
            builder: (BuildContext context, GoRouterState state) {
              return const ScreenB();
            },
            routes: <RouteBase>[
              /// Same as "/a/details", but displayed on the root Navigator by
              /// specifying [parentNavigatorKey]. This will cover both screen B
              /// and the application shell.
              GoRoute(
                path: 'details',
                parentNavigatorKey: _rootNavigatorKey,
                builder: (BuildContext context, GoRouterState state) {
                  return const DetailsScreen(label: 'B');
                },
              ),
            ],
          ),

          /// The third screen to display in the bottom navigation bar.
          GoRoute(
            path: '/c',
            builder: (BuildContext context, GoRouterState state) {
              return const ScreenC();
            },
            routes: <RouteBase>[
              // The details screen to display stacked on the inner Navigator.
              // This will cover screen A but not the application shell.
              GoRoute(
                path: 'details',
                builder: (BuildContext context, GoRouterState state) {
                  return const DetailsScreen(label: 'C');
                },
              ),
            ],
          )
        ],
      ),
    ],
  );

  @override
  Widget build(BuildContext context) {
    return CupertinoApp.router(
      title: 'Flutter Demo',
      routerConfig: _router,
    );
  }
}

class ScaffoldWithNavBar extends StatelessWidget {
  const ScaffoldWithNavBar({required this.child, Key? key}) : super(key: key);

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      tabBar: CupertinoTabBar(
        currentIndex: _calculateSelectedIndex(context),
        onTap: (int index) => _onItemTapped(index, context),
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'A Screen',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'B Screen',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.notification_important_rounded),
            label: 'C Screen',
          ),
        ],
      ),
      tabBuilder: (BuildContext context, int index) => child,
    );
  }

  int _calculateSelectedIndex(BuildContext context) {
    final GoRouter route = GoRouter.of(context);
    final String location = route.location;
    if (location.startsWith('/a')) {
      return 0;
    }
    if (location.startsWith('/b')) {
      return 1;
    }
    if (location.startsWith('/c')) {
      return 2;
    }
    return 0;
  }

  void _onItemTapped(int index, BuildContext context) {
    switch (index) {
      case 0:
        GoRouter.of(context).go('/a');
        break;
      case 1:
        GoRouter.of(context).go('/b');
        break;
      case 2:
        GoRouter.of(context).go('/c');
        break;
    }
  }
}

/// The first screen in the bottom navigation bar.
class ScreenA extends StatelessWidget {
  /// Constructs a [ScreenA] widget.
  const ScreenA({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const Text('Screen A'),
            TextButton(
              onPressed: () {
                GoRouter.of(context).go('/a/details');
              },
              child: const Text('View A details'),
            ),
          ],
        ),
      ),
    );
  }
}

/// The second screen in the bottom navigation bar.
class ScreenB extends StatelessWidget {
  /// Constructs a [ScreenB] widget.
  const ScreenB({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const Text('Screen B'),
            TextButton(
              onPressed: () {
                GoRouter.of(context).go('/b/details');
              },
              child: const Text('View B details'),
            ),
          ],
        ),
      ),
    );
  }
}

/// The third screen in the bottom navigation bar.
class ScreenC extends StatelessWidget {
  /// Constructs a [ScreenC] widget.
  const ScreenC({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const Text('Screen C'),
            TextButton(
              onPressed: () {
                GoRouter.of(context).go('/c/details');
              },
              child: const Text('View C details'),
            ),
          ],
        ),
      ),
    );
  }
}

class DetailsScreen extends StatelessWidget {
  const DetailsScreen({required this.label, Key? key}) : super(key: key);

  final String label;

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(
        middle: Text('Details Screen'),
      ),
      child: Center(
        child: Text(
          'Details for $label',
          style: Theme.of(context).textTheme.headlineMedium,
        ),
      ),
    );
  }
}
Logs
                    ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
                    The following assertion was thrown while finalizing the widget tree:
                    Multiple widgets used the same GlobalKey.
                    The key [LabeledGlobalKey<NavigatorState>#57aa1 shell] was used by multiple widgets. The parents of
                    those widgets were different widgets that both had the following description:
                      Builder
                    A GlobalKey can only be specified on one widget at a time in the widget tree.

                    When the exception was thrown, this was the stack:
                    #0      BuildOwner._debugVerifyGlobalKeyReservation.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/framework.dart:2883:13)
                    #1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:617:13)
                    #2      BuildOwner._debugVerifyGlobalKeyReservation.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/framework.dart:2827:20)
                    #3      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:617:13)
                    #4      BuildOwner._debugVerifyGlobalKeyReservation.<anonymous closure> (package:flutter/src/widgets/framework.dart:2822:36)
                    #5      BuildOwner._debugVerifyGlobalKeyReservation (package:flutter/src/widgets/framework.dart:2891:6)
                    #6      BuildOwner.finalizeTree.<anonymous closure> (package:flutter/src/widgets/framework.dart:2950:11)
                    #7      BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:3032:8)
                    #8      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:885:19)
                    #9      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:378:5)
                    #10     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1175:15)
                    #11     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1104:9)
                    #12     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1015:5)
                    #13     _invoke (dart:ui/hooks.dart:148:13)
                    #14     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:318:5)
                    #15     _drawFrame (dart:ui/hooks.dart:115:31)
                    ════════════════════════════════════════════════════════════════════════════════════════════════════
[  +48 ms] 
           Another exception was thrown: Multiple widgets used the same GlobalKey.
[  +43 ms] 
           Another exception was thrown: Multiple widgets used the same GlobalKey.
[  +84 ms] 
           Another exception was thrown: Multiple widgets used the same GlobalKey.
Analyzing bug...                                                        
No issues found! (ran in 4.1s)
[✓] Flutter (Channel stable, 3.3.4, on Microsoft Windows [Version 10.0.22621.674], locale en-US)
    • Flutter version 3.3.4 on channel stable at E:\ProgramData\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision eb6d86ee27 (2 weeks ago), 2022-10-04 22:31:45 -0700
    • Engine revision c08d7d5efc
    • Dart version 2.18.2
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at E:\ProgramData\Android\Sdk
    • Platform android-33, build-tools 33.0.0
    • ANDROID_HOME = E:\ProgramData\Android\Sdk
    • ANDROID_SDK_ROOT = E:\ProgramData\Android\Sdk
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✗] Chrome - develop for the web (Cannot find Chrome executable at .\Google\Chrome\Application\chrome.exe)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[✗] Visual Studio - develop for Windows
    ✗ Visual Studio not installed; this is necessary for Windows development.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components

[✓] Android Studio (version 2021.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] VS Code (version 1.72.2)
    • VS Code at C:\Users\user\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (3 available)
    • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64    • Android 13 (API 33) (emulator)
    • Windows (desktop)            • windows       • windows-x64    • Microsoft Windows [Version 10.0.22621.674]
    • Edge (web)                   • edge          • web-javascript • Microsoft Edge 106.0.1370.47

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 2 categories.

Activity

  1. added
    in triagePresently being triaged by the triage team
    on Oct 21, 2022
  2. huycozy commented on Oct 21, 2022

    @huycozy
    Member

    @emirhanaydin thanks for filing the issue. This issue is reproducible on the latest stable and master channels with provided sample code.

    flutter doctor -v (stable and master)
    [✓] Flutter (Channel stable, 3.3.5, on macOS 12.6 21G115 darwin-x64, locale en-VN)
        • Flutter version 3.3.5 on channel stable at /Users/huynq/Documents/GitHub/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision d9111f6402 (9 hours ago), 2022-10-19 12:27:13 -0700
        • Engine revision 3ad69d7be3
        • Dart version 2.18.2
        • DevTools version 2.15.0
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
        • Android SDK at /Users/huynq/Library/Android/sdk
        • Platform android-33, build-tools 31.0.0
        • ANDROID_HOME = /Users/huynq/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 14.0.1)
        • Xcode at /Applications/Xcode14.0.1.app/Contents/Developer
        • Build 14A400
        • CocoaPods version 1.11.3
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2021.3)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    
    [✓] IntelliJ IDEA Community Edition (version 2022.2.2)
        • IntelliJ at /Applications/IntelliJ IDEA CE.app
        • Flutter plugin version 70.0.5
        • Dart plugin version 222.4167.21
    
    [✓] IntelliJ IDEA Community Edition (version 2022.1.1)
        • IntelliJ at /Users/huynq/Library/Application Support/JetBrains/Toolbox/apps/IDEA-C/ch-0/221.5591.52/IntelliJ IDEA CE.app
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
    
    [✓] VS Code (version 1.72.1)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.50.0
    
    [✓] Connected device (3 available)
        • iPhone 14 Pro Max (mobile) • 332079AF-E895-4685-910E-7B1E18B0C6B8 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-0 (simulator)
        • macOS (desktop)            • macos                                • darwin-x64     • macOS 12.6 21G115 darwin-x64
        • Chrome (web)               • chrome                               • web-javascript • Google Chrome 106.0.5249.119
    
    [✓] HTTP Host Availability
        • All required HTTP hosts are available
    
    • No issues found!
    
    [!] Flutter (Channel master, 3.5.0-10.0.pre.17, on macOS 12.6 21G115 darwin-x64, locale en-VN)
        • Flutter version 3.5.0-10.0.pre.17 on channel master at /Users/huynq/Documents/GitHub/flutter_master
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 59d26c481a (4 hours ago), 2022-10-20 20:05:08 -0400
        • Engine revision f24ea1a04d
        • Dart version 2.19.0 (build 2.19.0-324.0.dev)
        • DevTools version 2.18.0
        • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
        • Android SDK at /Users/huynq/Library/Android/sdk
        • Platform android-33, build-tools 31.0.0
        • ANDROID_HOME = /Users/huynq/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 14.0.1)
        • Xcode at /Applications/Xcode14.0.1.app/Contents/Developer
        • Build 14A400
        • CocoaPods version 1.11.3
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2021.3)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    
    [✓] IntelliJ IDEA Community Edition (version 2022.2.2)
        • IntelliJ at /Applications/IntelliJ IDEA CE.app
        • Flutter plugin version 70.0.5
        • Dart plugin version 222.4167.21
    
    [✓] IntelliJ IDEA Community Edition (version 2022.1.1)
        • IntelliJ at /Users/huynq/Library/Application Support/JetBrains/Toolbox/apps/IDEA-C/ch-0/221.5591.52/IntelliJ IDEA CE.app
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
    
    [✓] VS Code (version 1.72.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.50.0
    
    [✓] Connected device (2 available)
        • macOS (desktop) • macos  • darwin-x64     • macOS 12.6 21G115 darwin-x64
        • Chrome (web)    • chrome • web-javascript • Google Chrome 106.0.5249.119
    
    [✓] HTTP Host Availability
        • All required HTTP hosts are available
    
    ! Doctor found issues in 1 category.
    
  3. added
    packageflutter/packages repository. See also p: labels.
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    and removed
    in triagePresently being triaged by the triage team
    on Oct 21, 2022
  4. rmoralesd commented on Oct 25, 2022

    @rmoralesd

    I'm having this same issue, but with simple stateless widgets in the tabs. In my case the app works as intended, but crashes when a change in the code is made and the hot reload is performed.
    This is the link of the code Sheel Route example
    Steps to reproduce:

    1. Run the code
    2. Make any change in the code
    3. Save to hot reload the app.

    Result:
    The app crashes withe the error:

    Multiple widgets used the same GlobalKey.

  5. janknips commented on Oct 26, 2022

    @janknips

    This breaks my entire use-case of go_router - just started migrating my routing to it and tried fixing this for 10 minutes before finding this issue. Also, supplying async redirect method crashes as well. I appreciate go_router a lot, it's great its being maintained, but the quality is not really where it should be. So far, when using go_router, whenever I thought something that was my fault, it is actually a package issue. 🤔

    Edit: tried refactoring to use Material Scaffold(), but still crashes with the same error. Strange.

  6. added
    P2Important issues not at the top of the work list
    on Oct 27, 2022
  7. hostr-sam commented on Dec 15, 2022

    @hostr-sam

    Experiencing this exact issue with CupertinoTabScaffold on stable with go_router 5.2.0.

    Works flawlessly with Material's Scaffold using the same GlobalKey setup. Move this exact implementation over to Cupertino and the app crashes with Multiple widgets used the same GlobalKey

    Super frustrating as I really want to use this router

  8. marcelweigle commented on Jan 16, 2023

    @marcelweigle

    I got the same problem. I am also refactoring to use go_router but this is a total showstopper because it basically only makes go_router work with Material and not with Cupertino.

    Disabling that key like @ska2519 did not solve my problem

  9. 34 remaining items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listfound in release: 3.3Found to occur in 3.3found in release: 3.5Found to occur in 3.5has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: go_routerThe go_router packagepackageflutter/packages repository. See also p: labels.team-ecosystemOwned by Ecosystem teamtriaged-ecosystemTriaged by Ecosystem team

    Type

    No type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions