├── .github └── workflows │ └── flutter.yml ├── .gitignore ├── .metadata ├── CHANGELOG.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── example ├── .gitignore ├── .metadata ├── README.md ├── analysis_options.yaml ├── android │ ├── .gitignore │ ├── app │ │ ├── build.gradle │ │ └── src │ │ │ ├── debug │ │ │ └── AndroidManifest.xml │ │ │ ├── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── kotlin │ │ │ │ └── com │ │ │ │ │ └── example │ │ │ │ │ └── example │ │ │ │ │ └── MainActivity.kt │ │ │ └── res │ │ │ │ ├── drawable-v21 │ │ │ │ └── launch_background.xml │ │ │ │ ├── drawable │ │ │ │ └── launch_background.xml │ │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ │ ├── values-night │ │ │ │ └── styles.xml │ │ │ │ └── values │ │ │ │ └── styles.xml │ │ │ └── profile │ │ │ └── AndroidManifest.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ └── gradle-wrapper.properties │ └── settings.gradle ├── ios │ ├── .gitignore │ ├── Flutter │ │ ├── AppFrameworkInfo.plist │ │ ├── Debug.xcconfig │ │ └── Release.xcconfig │ ├── Runner.xcodeproj │ │ ├── project.pbxproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ │ ├── IDEWorkspaceChecks.plist │ │ │ │ └── WorkspaceSettings.xcsettings │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ └── Runner.xcscheme │ ├── Runner.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ ├── IDEWorkspaceChecks.plist │ │ │ └── WorkspaceSettings.xcsettings │ └── Runner │ │ ├── AppDelegate.swift │ │ ├── Assets.xcassets │ │ ├── AppIcon.appiconset │ │ │ ├── Contents.json │ │ │ ├── Icon-App-1024x1024@1x.png │ │ │ ├── Icon-App-20x20@1x.png │ │ │ ├── Icon-App-20x20@2x.png │ │ │ ├── Icon-App-20x20@3x.png │ │ │ ├── Icon-App-29x29@1x.png │ │ │ ├── Icon-App-29x29@2x.png │ │ │ ├── Icon-App-29x29@3x.png │ │ │ ├── Icon-App-40x40@1x.png │ │ │ ├── Icon-App-40x40@2x.png │ │ │ ├── Icon-App-40x40@3x.png │ │ │ ├── Icon-App-60x60@2x.png │ │ │ ├── Icon-App-60x60@3x.png │ │ │ ├── Icon-App-76x76@1x.png │ │ │ ├── Icon-App-76x76@2x.png │ │ │ └── Icon-App-83.5x83.5@2x.png │ │ └── LaunchImage.imageset │ │ │ ├── Contents.json │ │ │ ├── LaunchImage.png │ │ │ ├── LaunchImage@2x.png │ │ │ ├── LaunchImage@3x.png │ │ │ └── README.md │ │ ├── Base.lproj │ │ ├── LaunchScreen.storyboard │ │ └── Main.storyboard │ │ ├── Info.plist │ │ └── Runner-Bridging-Header.h ├── lib │ ├── basics.dart │ ├── bottom_nav.dart │ ├── bottom_nav_with_navigator.dart │ ├── bottom_nav_with_tabs.dart │ ├── cupertino.dart │ ├── feature_splitting │ │ ├── listen_now.dart │ │ ├── main.dart │ │ ├── radio.dart │ │ └── song.dart │ ├── links.dart │ ├── path_parameters.dart │ ├── recursive_shell.dart │ ├── sign_in.dart │ ├── stacked_nested_nav.dart │ └── url_strategy.dart ├── pubspec.lock ├── pubspec.yaml ├── web │ ├── favicon.png │ ├── icons │ │ ├── Icon-192.png │ │ ├── Icon-512.png │ │ ├── Icon-maskable-192.png │ │ └── Icon-maskable-512.png │ ├── index.html │ └── manifest.json └── windows │ ├── .gitignore │ ├── CMakeLists.txt │ ├── flutter │ ├── CMakeLists.txt │ ├── generated_plugin_registrant.cc │ ├── generated_plugin_registrant.h │ └── generated_plugins.cmake │ └── runner │ ├── CMakeLists.txt │ ├── Runner.rc │ ├── flutter_window.cpp │ ├── flutter_window.h │ ├── main.cpp │ ├── resource.h │ ├── resources │ └── app_icon.ico │ ├── runner.exe.manifest │ ├── utils.cpp │ ├── utils.h │ ├── win32_window.cpp │ └── win32_window.h ├── lib ├── go_router_prototype.dart └── src │ ├── builder.dart │ ├── delegate.dart │ ├── inheritance.dart │ ├── match.dart │ ├── matching.dart │ ├── parameters.dart │ ├── parser.dart │ ├── route.dart │ ├── state.dart │ ├── tree.dart │ └── typedefs.dart ├── pubspec.yaml └── test ├── builder_test.dart ├── delegate_test.dart ├── helpers.dart ├── matcher_test.dart ├── redirect_test.dart ├── route_match_test.dart ├── route_state_test.dart ├── route_test.dart └── tree_test.dart /.github/workflows/flutter.yml: -------------------------------------------------------------------------------- 1 | name: Flutter CI 2 | on: push 3 | jobs: 4 | test-package: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v1 8 | - uses: subosito/flutter-action@v1 9 | with: 10 | channel: 'stable' 11 | - run: flutter pub get 12 | - run: flutter format --set-exit-if-changed . 13 | - run: flutter analyze . 14 | - run: flutter test -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | 12 | # IntelliJ related 13 | *.iml 14 | *.ipr 15 | *.iws 16 | .idea/ 17 | 18 | # The .vscode folder contains launch configuration and tasks you configure in 19 | # VS Code which you may wish to be included in version control, so this line 20 | # is commented out by default. 21 | #.vscode/ 22 | 23 | # Flutter/Dart/Pub related 24 | # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. 25 | /pubspec.lock 26 | **/doc/api/ 27 | .dart_tool/ 28 | .packages 29 | build/ 30 | -------------------------------------------------------------------------------- /.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: 7e9793dee1b85a243edd0e06cb1658e98b077561 8 | channel: stable 9 | 10 | project_type: package 11 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.1.0 2 | 3 | * Add refreshListenable and sign-in sample 4 | 5 | ## 0.0.1 6 | 7 | * Initial release. 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2013 The Flutter Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without modification, 4 | are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above 9 | copyright notice, this list of conditions and the following 10 | disclaimer in the documentation and/or other materials provided 11 | with the distribution. 12 | * Neither the name of Google Inc. nor the names of its 13 | contributors may be used to endorse or promote products derived 14 | from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 20 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 23 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | GoRouter API prototype. See the [design doc](https://docs.google.com/document/d/1_mRXinbL_rb0mUt6DAFZ8kj0kh33ZjEMJuUq4PJgwj8/edit?usp=sharing&resourcekey=0-sYbRzE9opneOFZ5F8J3gGw) for more information. 2 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:flutter_lints/flutter.yaml 2 | 3 | # Additional information about this file can be found at 4 | # https://dart.dev/guides/language/analysis-options 5 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | 12 | # IntelliJ related 13 | *.iml 14 | *.ipr 15 | *.iws 16 | .idea/ 17 | 18 | # The .vscode folder contains launch configuration and tasks you configure in 19 | # VS Code which you may wish to be included in version control, so this line 20 | # is commented out by default. 21 | #.vscode/ 22 | 23 | # Flutter/Dart/Pub related 24 | **/doc/api/ 25 | **/ios/Flutter/.last_build_id 26 | .dart_tool/ 27 | .flutter-plugins 28 | .flutter-plugins-dependencies 29 | .packages 30 | .pub-cache/ 31 | .pub/ 32 | /build/ 33 | 34 | # Web related 35 | lib/generated_plugin_registrant.dart 36 | 37 | # Symbolication related 38 | app.*.symbols 39 | 40 | # Obfuscation related 41 | app.*.map.json 42 | 43 | # Android Studio will place build artifacts here 44 | /android/app/debug 45 | /android/app/profile 46 | /android/app/release 47 | -------------------------------------------------------------------------------- /example/.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: 7e9793dee1b85a243edd0e06cb1658e98b077561 8 | channel: stable 9 | 10 | project_type: app 11 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/README.md -------------------------------------------------------------------------------- /example/analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the analyzer, which statically analyzes Dart code to 2 | # check for errors, warnings, and lints. 3 | # 4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled 5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be 6 | # invoked from the command line by running `flutter analyze`. 7 | 8 | # The following line activates a set of recommended lints for Flutter apps, 9 | # packages, and plugins designed to encourage good coding practices. 10 | include: package:flutter_lints/flutter.yaml 11 | 12 | linter: 13 | # The lint rules applied to this project can be customized in the 14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml` 15 | # included above or to enable additional rules. A list of all available lints 16 | # and their documentation is published at 17 | # https://dart-lang.github.io/linter/lints/index.html. 18 | # 19 | # Instead of disabling a lint rule for the entire project in the 20 | # section below, it can also be suppressed for a single line of code 21 | # or a specific dart file by using the `// ignore: name_of_lint` and 22 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file 23 | # producing the lint. 24 | rules: 25 | # avoid_print: false # Uncomment to disable the `avoid_print` rule 26 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule 27 | 28 | # Additional information about this file can be found at 29 | # https://dart.dev/guides/language/analysis-options 30 | -------------------------------------------------------------------------------- /example/android/.gitignore: -------------------------------------------------------------------------------- 1 | gradle-wrapper.jar 2 | /.gradle 3 | /captures/ 4 | /gradlew 5 | /gradlew.bat 6 | /local.properties 7 | GeneratedPluginRegistrant.java 8 | 9 | # Remember to never publicly share your keystore. 10 | # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app 11 | key.properties 12 | **/*.keystore 13 | **/*.jks 14 | -------------------------------------------------------------------------------- /example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | def localProperties = new Properties() 2 | def localPropertiesFile = rootProject.file('local.properties') 3 | if (localPropertiesFile.exists()) { 4 | localPropertiesFile.withReader('UTF-8') { reader -> 5 | localProperties.load(reader) 6 | } 7 | } 8 | 9 | def flutterRoot = localProperties.getProperty('flutter.sdk') 10 | if (flutterRoot == null) { 11 | throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") 12 | } 13 | 14 | def flutterVersionCode = localProperties.getProperty('flutter.versionCode') 15 | if (flutterVersionCode == null) { 16 | flutterVersionCode = '1' 17 | } 18 | 19 | def flutterVersionName = localProperties.getProperty('flutter.versionName') 20 | if (flutterVersionName == null) { 21 | flutterVersionName = '1.0' 22 | } 23 | 24 | apply plugin: 'com.android.application' 25 | apply plugin: 'kotlin-android' 26 | apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" 27 | 28 | android { 29 | compileSdkVersion flutter.compileSdkVersion 30 | 31 | compileOptions { 32 | sourceCompatibility JavaVersion.VERSION_1_8 33 | targetCompatibility JavaVersion.VERSION_1_8 34 | } 35 | 36 | kotlinOptions { 37 | jvmTarget = '1.8' 38 | } 39 | 40 | sourceSets { 41 | main.java.srcDirs += 'src/main/kotlin' 42 | } 43 | 44 | defaultConfig { 45 | // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). 46 | applicationId "com.example.example" 47 | minSdkVersion flutter.minSdkVersion 48 | targetSdkVersion flutter.targetSdkVersion 49 | versionCode flutterVersionCode.toInteger() 50 | versionName flutterVersionName 51 | } 52 | 53 | buildTypes { 54 | release { 55 | // TODO: Add your own signing config for the release build. 56 | // Signing with the debug keys for now, so `flutter run --release` works. 57 | signingConfig signingConfigs.debug 58 | } 59 | } 60 | } 61 | 62 | flutter { 63 | source '../..' 64 | } 65 | 66 | dependencies { 67 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 68 | } 69 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 7 | 15 | 19 | 23 | 24 | 25 | 26 | 27 | 28 | 30 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /example/android/app/src/main/kotlin/com/example/example/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.example.example 2 | 3 | import io.flutter.embedding.android.FlutterActivity 4 | 5 | class MainActivity: FlutterActivity() { 6 | } 7 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable-v21/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/values-night/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /example/android/app/src/profile/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlin_version = '1.6.10' 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:4.1.0' 10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 11 | } 12 | } 13 | 14 | allprojects { 15 | repositories { 16 | google() 17 | mavenCentral() 18 | } 19 | } 20 | 21 | rootProject.buildDir = '../build' 22 | subprojects { 23 | project.buildDir = "${rootProject.buildDir}/${project.name}" 24 | } 25 | subprojects { 26 | project.evaluationDependsOn(':app') 27 | } 28 | 29 | task clean(type: Delete) { 30 | delete rootProject.buildDir 31 | } 32 | -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx1536M 2 | android.useAndroidX=true 3 | android.enableJetifier=true 4 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Jun 23 08:50:38 CEST 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip 7 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | 3 | def localPropertiesFile = new File(rootProject.projectDir, "local.properties") 4 | def properties = new Properties() 5 | 6 | assert localPropertiesFile.exists() 7 | localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } 8 | 9 | def flutterSdkPath = properties.getProperty("flutter.sdk") 10 | assert flutterSdkPath != null, "flutter.sdk not set in local.properties" 11 | apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" 12 | -------------------------------------------------------------------------------- /example/ios/.gitignore: -------------------------------------------------------------------------------- 1 | **/dgph 2 | *.mode1v3 3 | *.mode2v3 4 | *.moved-aside 5 | *.pbxuser 6 | *.perspectivev3 7 | **/*sync/ 8 | .sconsign.dblite 9 | .tags* 10 | **/.vagrant/ 11 | **/DerivedData/ 12 | Icon? 13 | **/Pods/ 14 | **/.symlinks/ 15 | profile 16 | xcuserdata 17 | **/.generated/ 18 | Flutter/App.framework 19 | Flutter/Flutter.framework 20 | Flutter/Flutter.podspec 21 | Flutter/Generated.xcconfig 22 | Flutter/ephemeral/ 23 | Flutter/app.flx 24 | Flutter/app.zip 25 | Flutter/flutter_assets/ 26 | Flutter/flutter_export_environment.sh 27 | ServiceDefinitions.json 28 | Runner/GeneratedPluginRegistrant.* 29 | 30 | # Exceptions to above rules. 31 | !default.mode1v3 32 | !default.mode2v3 33 | !default.pbxuser 34 | !default.perspectivev3 35 | -------------------------------------------------------------------------------- /example/ios/Flutter/AppFrameworkInfo.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | App 9 | CFBundleIdentifier 10 | io.flutter.flutter.app 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | App 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1.0 23 | MinimumOSVersion 24 | 9.0 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/ios/Flutter/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" 2 | #include "Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/ios/Flutter/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" 2 | #include "Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 52 | 54 | 60 | 61 | 62 | 63 | 69 | 71 | 77 | 78 | 79 | 80 | 82 | 83 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | import Flutter 3 | 4 | @UIApplicationMain 5 | @objc class AppDelegate: FlutterAppDelegate { 6 | override func application( 7 | _ application: UIApplication, 8 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? 9 | ) -> Bool { 10 | GeneratedPluginRegistrant.register(with: self) 11 | return super.application(application, didFinishLaunchingWithOptions: launchOptions) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "20x20", 5 | "idiom" : "iphone", 6 | "filename" : "Icon-App-20x20@2x.png", 7 | "scale" : "2x" 8 | }, 9 | { 10 | "size" : "20x20", 11 | "idiom" : "iphone", 12 | "filename" : "Icon-App-20x20@3x.png", 13 | "scale" : "3x" 14 | }, 15 | { 16 | "size" : "29x29", 17 | "idiom" : "iphone", 18 | "filename" : "Icon-App-29x29@1x.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "29x29", 23 | "idiom" : "iphone", 24 | "filename" : "Icon-App-29x29@2x.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "29x29", 29 | "idiom" : "iphone", 30 | "filename" : "Icon-App-29x29@3x.png", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "size" : "40x40", 35 | "idiom" : "iphone", 36 | "filename" : "Icon-App-40x40@2x.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "40x40", 41 | "idiom" : "iphone", 42 | "filename" : "Icon-App-40x40@3x.png", 43 | "scale" : "3x" 44 | }, 45 | { 46 | "size" : "60x60", 47 | "idiom" : "iphone", 48 | "filename" : "Icon-App-60x60@2x.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "60x60", 53 | "idiom" : "iphone", 54 | "filename" : "Icon-App-60x60@3x.png", 55 | "scale" : "3x" 56 | }, 57 | { 58 | "size" : "20x20", 59 | "idiom" : "ipad", 60 | "filename" : "Icon-App-20x20@1x.png", 61 | "scale" : "1x" 62 | }, 63 | { 64 | "size" : "20x20", 65 | "idiom" : "ipad", 66 | "filename" : "Icon-App-20x20@2x.png", 67 | "scale" : "2x" 68 | }, 69 | { 70 | "size" : "29x29", 71 | "idiom" : "ipad", 72 | "filename" : "Icon-App-29x29@1x.png", 73 | "scale" : "1x" 74 | }, 75 | { 76 | "size" : "29x29", 77 | "idiom" : "ipad", 78 | "filename" : "Icon-App-29x29@2x.png", 79 | "scale" : "2x" 80 | }, 81 | { 82 | "size" : "40x40", 83 | "idiom" : "ipad", 84 | "filename" : "Icon-App-40x40@1x.png", 85 | "scale" : "1x" 86 | }, 87 | { 88 | "size" : "40x40", 89 | "idiom" : "ipad", 90 | "filename" : "Icon-App-40x40@2x.png", 91 | "scale" : "2x" 92 | }, 93 | { 94 | "size" : "76x76", 95 | "idiom" : "ipad", 96 | "filename" : "Icon-App-76x76@1x.png", 97 | "scale" : "1x" 98 | }, 99 | { 100 | "size" : "76x76", 101 | "idiom" : "ipad", 102 | "filename" : "Icon-App-76x76@2x.png", 103 | "scale" : "2x" 104 | }, 105 | { 106 | "size" : "83.5x83.5", 107 | "idiom" : "ipad", 108 | "filename" : "Icon-App-83.5x83.5@2x.png", 109 | "scale" : "2x" 110 | }, 111 | { 112 | "size" : "1024x1024", 113 | "idiom" : "ios-marketing", 114 | "filename" : "Icon-App-1024x1024@1x.png", 115 | "scale" : "1x" 116 | } 117 | ], 118 | "info" : { 119 | "version" : 1, 120 | "author" : "xcode" 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "LaunchImage.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "LaunchImage@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "LaunchImage@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png -------------------------------------------------------------------------------- /example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md: -------------------------------------------------------------------------------- 1 | # Launch Screen Assets 2 | 3 | You can customize the launch screen with your own desired assets by replacing the image files in this directory. 4 | 5 | You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. -------------------------------------------------------------------------------- /example/ios/Runner/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /example/ios/Runner/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /example/ios/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleDisplayName 8 | Example 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | example 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | $(FLUTTER_BUILD_NUMBER) 25 | LSRequiresIPhoneOS 26 | 27 | UILaunchStoryboardName 28 | LaunchScreen 29 | UIMainStoryboardFile 30 | Main 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UISupportedInterfaceOrientations~ipad 38 | 39 | UIInterfaceOrientationPortrait 40 | UIInterfaceOrientationPortraitUpsideDown 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | UIViewControllerBasedStatusBarAppearance 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /example/ios/Runner/Runner-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | #import "GeneratedPluginRegistrant.h" 2 | -------------------------------------------------------------------------------- /example/lib/basics.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/go_router_prototype.dart'; 7 | 8 | void main() { 9 | runApp(ExampleApp()); 10 | } 11 | 12 | class ExampleApp extends StatelessWidget { 13 | ExampleApp({Key? key}) : super(key: key); 14 | 15 | final _router = GoRouter( 16 | routes: [ 17 | StackedRoute( 18 | path: '/', 19 | builder: (context) => const AScreen(), 20 | routes: [ 21 | StackedRoute( 22 | path: 'b', 23 | builder: (context) => const BScreen(), 24 | ), 25 | ], 26 | ), 27 | StackedRoute( 28 | path: '/c', 29 | builder: (context) => const CScreen(), 30 | ), 31 | ], 32 | ); 33 | 34 | @override 35 | Widget build(BuildContext context) { 36 | return MaterialApp.router( 37 | routerDelegate: _router.delegate, 38 | routeInformationParser: _router.parser, 39 | ); 40 | } 41 | } 42 | 43 | class AScreen extends Screen { 44 | const AScreen({Key? key}) 45 | : super( 46 | key: key, 47 | name: 'Screen A', 48 | linkTo: 'b', 49 | ); 50 | } 51 | 52 | class BScreen extends Screen { 53 | const BScreen({Key? key}) 54 | : super( 55 | key: key, 56 | name: 'Screen B', 57 | linkTo: '/c', 58 | ); 59 | } 60 | 61 | class CScreen extends Screen { 62 | const CScreen({Key? key}) 63 | : super( 64 | key: key, 65 | name: 'Screen C', 66 | linkTo: '/a', 67 | ); 68 | } 69 | 70 | class Screen extends StatelessWidget { 71 | final String name; 72 | final String linkTo; 73 | 74 | const Screen({ 75 | required this.name, 76 | required this.linkTo, 77 | Key? key, 78 | }) : super(key: key); 79 | 80 | @override 81 | Widget build(BuildContext context) { 82 | return Scaffold( 83 | appBar: AppBar( 84 | title: const Text('Basics'), 85 | ), 86 | body: Center( 87 | child: Column( 88 | mainAxisAlignment: MainAxisAlignment.center, 89 | children: [ 90 | Text( 91 | name, 92 | style: Theme.of(context).textTheme.headline4, 93 | ), 94 | TextButton( 95 | child: Text('Go to $linkTo'), 96 | onPressed: () { 97 | RouteState.of(context).goTo(linkTo); 98 | }, 99 | ), 100 | ], 101 | ), 102 | ), 103 | ); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /example/lib/bottom_nav.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/go_router_prototype.dart'; 7 | 8 | void main() { 9 | runApp(BottomNavigationBarDemo()); 10 | } 11 | 12 | class BottomNavigationBarDemo extends StatelessWidget { 13 | BottomNavigationBarDemo({Key? key}) : super(key: key); 14 | 15 | final _router = GoRouter( 16 | routes: [ 17 | ShellRoute( 18 | path: '/', 19 | builder: (context, child) => AppScaffold(child: child), 20 | // preserveState: true, 21 | routes: [ 22 | StackedRoute( 23 | path: 'a', 24 | builder: (context) => const Screen( 25 | title: 'Screen A', 26 | key: ValueKey('A'), 27 | ), 28 | routes: [ 29 | StackedRoute( 30 | path: 'details', 31 | builder: (context) => const DetailsScreen(label: 'A'), 32 | ), 33 | ], 34 | ), 35 | NestedStackRoute( 36 | path: 'b', 37 | builder: (context) => const Screen( 38 | title: 'Screen B', 39 | key: ValueKey('B'), 40 | ), 41 | routes: [ 42 | StackedRoute( 43 | path: 'details', 44 | builder: (context) => const DetailsScreen(label: 'B'), 45 | ), 46 | ], 47 | ), 48 | ], 49 | ), 50 | ], 51 | ); 52 | 53 | @override 54 | Widget build(BuildContext context) { 55 | return MaterialApp.router( 56 | routerDelegate: _router.delegate, 57 | routeInformationParser: _router.parser, 58 | ); 59 | } 60 | } 61 | 62 | class AppScaffold extends StatelessWidget { 63 | final Widget child; 64 | 65 | const AppScaffold({ 66 | required this.child, 67 | Key? key, 68 | }) : super(key: key); 69 | 70 | @override 71 | Widget build(BuildContext context) { 72 | final selectedIndex = _calculateSelectedIndex(context); 73 | return Scaffold( 74 | body: AnimatedSwitcher( 75 | duration: const Duration(milliseconds: 300), 76 | child: child, 77 | ), 78 | bottomNavigationBar: BottomNavigationBar( 79 | items: const [ 80 | BottomNavigationBarItem( 81 | icon: Icon(Icons.home), 82 | label: 'A Screen', 83 | ), 84 | BottomNavigationBarItem( 85 | icon: Icon(Icons.business), 86 | label: 'B Screen', 87 | ), 88 | ], 89 | currentIndex: selectedIndex, 90 | onTap: (idx) => _onItemTapped(idx, context), 91 | ), 92 | ); 93 | } 94 | 95 | static int _calculateSelectedIndex(BuildContext context) { 96 | final route = RouteState.of(context); 97 | final activeChild = route.activeChild; 98 | if (activeChild != null) { 99 | if (activeChild.path == 'a') return 0; 100 | if (activeChild.path == 'b') return 1; 101 | } 102 | return 0; 103 | } 104 | 105 | void _onItemTapped(int index, BuildContext context) { 106 | switch (index) { 107 | case 0: 108 | RouteState.of(context).goTo('a'); 109 | break; 110 | case 1: 111 | RouteState.of(context).goTo('b'); 112 | break; 113 | } 114 | } 115 | } 116 | 117 | class Screen extends StatelessWidget { 118 | final String title; 119 | 120 | const Screen({required this.title, Key? key}) : super(key: key); 121 | 122 | @override 123 | Widget build(BuildContext context) { 124 | return Center( 125 | child: Column( 126 | mainAxisAlignment: MainAxisAlignment.center, 127 | children: [ 128 | Text( 129 | title, 130 | style: Theme.of(context).textTheme.headline4, 131 | ), 132 | TextButton( 133 | onPressed: () { 134 | RouteState.of(context).goTo('details'); 135 | }, 136 | child: const Text('View details'), 137 | ), 138 | ], 139 | ), 140 | ); 141 | } 142 | } 143 | 144 | class DetailsScreen extends StatelessWidget { 145 | final String label; 146 | 147 | const DetailsScreen({required this.label, Key? key}) : super(key: key); 148 | 149 | @override 150 | Widget build(BuildContext context) { 151 | return Scaffold( 152 | appBar: AppBar( 153 | title: const Text('Bottom Nav'), 154 | ), 155 | body: Center( 156 | child: Text( 157 | 'Details for $label', 158 | style: Theme.of(context).textTheme.headline4, 159 | ), 160 | ), 161 | ); 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /example/lib/bottom_nav_with_navigator.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/go_router_prototype.dart'; 7 | 8 | void main() { 9 | runApp(BottomNavigationBarDemo()); 10 | } 11 | 12 | class BottomNavigationBarDemo extends StatelessWidget { 13 | BottomNavigationBarDemo({Key? key}) : super(key: key); 14 | 15 | final _router = GoRouter( 16 | routes: [ 17 | ShellRoute( 18 | path: '/', 19 | defaultRoute: 'a', 20 | builder: (context, child) => AppScaffold(child: child), 21 | routes: [ 22 | NestedStackRoute( 23 | path: 'a', 24 | builder: (context) => const Screen( 25 | title: 'Screen A', 26 | key: ValueKey('A'), 27 | ), 28 | routes: [ 29 | StackedRoute( 30 | path: 'details', 31 | builder: (context) => const DetailsScreen(label: 'A'), 32 | ), 33 | ], 34 | ), 35 | NestedStackRoute( 36 | path: 'b', 37 | builder: (context) => const Screen( 38 | title: 'Screen B', 39 | key: ValueKey('B'), 40 | ), 41 | routes: [ 42 | StackedRoute( 43 | path: 'details', 44 | builder: (context) => const DetailsScreen(label: 'B'), 45 | ), 46 | ], 47 | ), 48 | ], 49 | ), 50 | ], 51 | ); 52 | 53 | @override 54 | Widget build(BuildContext context) { 55 | return MaterialApp.router( 56 | routerDelegate: _router.delegate, 57 | routeInformationParser: _router.parser, 58 | ); 59 | } 60 | } 61 | 62 | class AppScaffold extends StatelessWidget { 63 | final Widget child; 64 | 65 | const AppScaffold({ 66 | required this.child, 67 | Key? key, 68 | }) : super(key: key); 69 | 70 | @override 71 | Widget build(BuildContext context) { 72 | final selectedIndex = _calculateSelectedIndex(context); 73 | return Scaffold( 74 | appBar: AppBar( 75 | title: const Text('Bottom Nav with inner Navigator'), 76 | ), 77 | body: AnimatedSwitcher( 78 | duration: const Duration(milliseconds: 300), 79 | child: child, 80 | ), 81 | bottomNavigationBar: BottomNavigationBar( 82 | items: const [ 83 | BottomNavigationBarItem( 84 | icon: Icon(Icons.home), 85 | label: 'A Screen', 86 | ), 87 | BottomNavigationBarItem( 88 | icon: Icon(Icons.business), 89 | label: 'B Screen', 90 | ), 91 | ], 92 | currentIndex: selectedIndex, 93 | onTap: (idx) => _onItemTapped(idx, context), 94 | ), 95 | ); 96 | } 97 | 98 | static int _calculateSelectedIndex(BuildContext context) { 99 | final route = RouteState.of(context); 100 | final activeChild = route.activeChild; 101 | if (activeChild != null) { 102 | if (activeChild.path == 'a') return 0; 103 | if (activeChild.path == 'b') return 1; 104 | } 105 | return 0; 106 | } 107 | 108 | void _onItemTapped(int index, BuildContext context) { 109 | switch (index) { 110 | case 0: 111 | RouteState.of(context).goTo('a'); 112 | break; 113 | case 1: 114 | RouteState.of(context).goTo('b'); 115 | break; 116 | } 117 | } 118 | } 119 | 120 | class Screen extends StatelessWidget { 121 | final String title; 122 | 123 | const Screen({required this.title, Key? key}) : super(key: key); 124 | 125 | @override 126 | Widget build(BuildContext context) { 127 | return Center( 128 | child: Column( 129 | mainAxisAlignment: MainAxisAlignment.center, 130 | children: [ 131 | Text( 132 | title, 133 | style: Theme.of(context).textTheme.headline4, 134 | ), 135 | TextButton( 136 | onPressed: () { 137 | RouteState.of(context).goTo('details'); 138 | }, 139 | child: const Text('View details'), 140 | ), 141 | ], 142 | ), 143 | ); 144 | } 145 | } 146 | 147 | class DetailsScreen extends StatelessWidget { 148 | final String label; 149 | 150 | const DetailsScreen({required this.label, Key? key}) : super(key: key); 151 | 152 | @override 153 | Widget build(BuildContext context) { 154 | return Scaffold( 155 | appBar: AppBar(), 156 | body: Center( 157 | child: Text( 158 | 'Details for $label', 159 | style: Theme.of(context).textTheme.headline4, 160 | ), 161 | ), 162 | ); 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /example/lib/bottom_nav_with_tabs.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/go_router_prototype.dart'; 7 | 8 | void main() { 9 | runApp(BottomNavWithTabsDemo()); 10 | } 11 | 12 | class BottomNavWithTabsDemo extends StatelessWidget { 13 | BottomNavWithTabsDemo({Key? key}) : super(key: key); 14 | 15 | final _router = GoRouter( 16 | routes: [ 17 | ShellRoute( 18 | path: '/', 19 | defaultRoute: 'books', 20 | builder: (context, child) { 21 | return AppScaffold(child: child); 22 | }, 23 | routes: [ 24 | ShellRoute( 25 | path: 'books', 26 | defaultRoute: 'popular', 27 | builder: (context, child) { 28 | return TabScreen( 29 | selectedIndex: _calculateTabIndex(context), 30 | child: child, 31 | ); 32 | }, 33 | routes: [ 34 | StackedRoute( 35 | path: 'popular', 36 | builder: (context) { 37 | return const PopularScreen(); 38 | }, 39 | ), 40 | StackedRoute( 41 | path: 'all', 42 | builder: (context) { 43 | return const AllScreen(); 44 | }, 45 | ), 46 | ], 47 | ), 48 | StackedRoute( 49 | path: 'settings', 50 | builder: (context) { 51 | return const SettingsScreen(); 52 | }, 53 | ), 54 | ], 55 | ), 56 | ], 57 | ); 58 | 59 | static int _calculateTabIndex(BuildContext context) { 60 | final route = RouteState.of(context); 61 | final activeChild = route.activeChild; 62 | if (activeChild != null) { 63 | if (activeChild.path == 'popular') return 0; 64 | if (activeChild.path == 'all') return 1; 65 | } 66 | return 0; 67 | } 68 | 69 | @override 70 | Widget build(BuildContext context) { 71 | return MaterialApp.router( 72 | routerDelegate: _router.delegate, 73 | routeInformationParser: _router.parser, 74 | ); 75 | } 76 | } 77 | 78 | class AppScaffold extends StatelessWidget { 79 | final Widget child; 80 | 81 | const AppScaffold({ 82 | required this.child, 83 | Key? key, 84 | }) : super(key: key); 85 | 86 | @override 87 | Widget build(BuildContext context) { 88 | final selectedIndex = _calculateSelectedIndex(context); 89 | return Scaffold( 90 | appBar: AppBar(), 91 | body: AnimatedSwitcher( 92 | duration: const Duration(milliseconds: 300), 93 | child: child, 94 | ), 95 | bottomNavigationBar: BottomNavigationBar( 96 | items: const [ 97 | BottomNavigationBarItem( 98 | icon: Icon(Icons.local_library), 99 | label: 'Books', 100 | ), 101 | BottomNavigationBarItem( 102 | icon: Icon(Icons.settings), 103 | label: 'Settings', 104 | ), 105 | ], 106 | currentIndex: selectedIndex, 107 | onTap: (idx) => _onItemTapped(idx, context), 108 | ), 109 | ); 110 | } 111 | 112 | static int _calculateSelectedIndex(BuildContext context) { 113 | final route = RouteState.of(context); 114 | final activeChild = route.activeChild; 115 | if (activeChild != null) { 116 | if (activeChild.path == 'books') return 0; 117 | if (activeChild.path == 'settings') return 1; 118 | } 119 | return 0; 120 | } 121 | 122 | void _onItemTapped(int index, BuildContext context) { 123 | switch (index) { 124 | case 0: 125 | RouteState.of(context).goTo('books'); 126 | break; 127 | case 1: 128 | RouteState.of(context).goTo('settings'); 129 | break; 130 | } 131 | } 132 | } 133 | 134 | class TabScreen extends StatefulWidget { 135 | final Widget child; 136 | final int selectedIndex; 137 | 138 | const TabScreen({ 139 | Key? key, 140 | required this.selectedIndex, 141 | required this.child, 142 | }) : super(key: key); 143 | 144 | @override 145 | _TabScreenState createState() => _TabScreenState(); 146 | } 147 | 148 | class _TabScreenState extends State 149 | with SingleTickerProviderStateMixin { 150 | late final TabController _tabController; 151 | 152 | @override 153 | void initState() { 154 | super.initState(); 155 | 156 | _tabController = TabController( 157 | length: 2, vsync: this, initialIndex: widget.selectedIndex); 158 | } 159 | 160 | @override 161 | void didUpdateWidget(TabScreen oldWidget) { 162 | super.didUpdateWidget(oldWidget); 163 | _tabController.index = widget.selectedIndex; 164 | } 165 | 166 | @override 167 | void dispose() { 168 | _tabController.dispose(); 169 | super.dispose(); 170 | } 171 | 172 | void _handleTabSelected(int index) { 173 | late final String path; 174 | switch (index) { 175 | case 0: 176 | path = 'popular'; 177 | break; 178 | case 1: 179 | path = 'all'; 180 | break; 181 | } 182 | RouteState.of(context).goTo(path); 183 | } 184 | 185 | @override 186 | Widget build(BuildContext context) { 187 | return Column( 188 | children: [ 189 | TabBar( 190 | controller: _tabController, 191 | onTap: _handleTabSelected, 192 | labelColor: Theme.of(context).primaryColor, 193 | tabs: const [ 194 | Tab(icon: Icon(Icons.lightbulb_outline), text: 'Popular'), 195 | Tab(icon: Icon(Icons.list), text: 'All'), 196 | ], 197 | ), 198 | AnimatedSwitcher( 199 | duration: const Duration(milliseconds: 300), 200 | child: widget.child, 201 | ), 202 | ], 203 | ); 204 | } 205 | } 206 | 207 | class AllScreen extends StatelessWidget { 208 | const AllScreen({Key? key}) : super(key: key); 209 | 210 | @override 211 | Widget build(BuildContext context) { 212 | return Column( 213 | crossAxisAlignment: CrossAxisAlignment.stretch, 214 | children: [ 215 | Center( 216 | child: Text('All', style: Theme.of(context).textTheme.headline4)), 217 | ], 218 | ); 219 | } 220 | } 221 | 222 | class PopularScreen extends StatelessWidget { 223 | const PopularScreen({Key? key}) : super(key: key); 224 | 225 | @override 226 | Widget build(BuildContext context) { 227 | return Column( 228 | crossAxisAlignment: CrossAxisAlignment.stretch, 229 | children: [ 230 | Center( 231 | child: 232 | Text('Popular', style: Theme.of(context).textTheme.headline4)), 233 | ], 234 | ); 235 | } 236 | } 237 | 238 | class SettingsScreen extends StatelessWidget { 239 | const SettingsScreen({Key? key}) : super(key: key); 240 | 241 | @override 242 | Widget build(BuildContext context) { 243 | return Column( 244 | crossAxisAlignment: CrossAxisAlignment.stretch, 245 | children: [ 246 | Center( 247 | child: 248 | Text('Settings', style: Theme.of(context).textTheme.headline4)), 249 | ], 250 | ); 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /example/lib/feature_splitting/listen_now.dart: -------------------------------------------------------------------------------- 1 | import 'package:adaptive_navigation/adaptive_navigation.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:go_router_prototype/go_router_prototype.dart'; 4 | 5 | import 'song.dart'; 6 | 7 | class ListenNowFeature extends StatelessWidget { 8 | static RouteBase route = StackedRoute( 9 | path: 'listen-now', 10 | builder: (context) => const ListenNowFeature(), 11 | routes: [ 12 | StackedRoute( 13 | path: 'song/:songId', 14 | builder: (context) => const SongScreen(), 15 | ), 16 | ], 17 | ); 18 | 19 | static const destination = AdaptiveScaffoldDestination( 20 | title: 'Listen now', 21 | icon: Icons.play_arrow, 22 | ); 23 | 24 | const ListenNowFeature({Key? key}) : super(key: key); 25 | 26 | @override 27 | Widget build(BuildContext context) { 28 | return Center( 29 | child: Column( 30 | children: [ 31 | Text( 32 | 'Listen Now', 33 | style: Theme.of(context).textTheme.headline5, 34 | ), 35 | TextButton( 36 | onPressed: () { 37 | RouteState.of(context).goTo('song/123'); 38 | }, 39 | child: const Text('View song 123'), 40 | ), 41 | ], 42 | ), 43 | ); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /example/lib/feature_splitting/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:adaptive_navigation/adaptive_navigation.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:go_router_prototype/go_router_prototype.dart'; 4 | 5 | import 'listen_now.dart'; 6 | import 'radio.dart'; 7 | 8 | void main() { 9 | runApp(FeatureSplittingDemo()); 10 | } 11 | 12 | class Feature { 13 | final RouteBase route; 14 | final AdaptiveScaffoldDestination destination; 15 | 16 | Feature(this.route, this.destination); 17 | } 18 | 19 | final List features = [ 20 | Feature(ListenNowFeature.route, ListenNowFeature.destination), 21 | Feature(RadioFeature.route, RadioFeature.destination), 22 | ]; 23 | 24 | class FeatureSplittingDemo extends StatelessWidget { 25 | FeatureSplittingDemo({Key? key}) : super(key: key); 26 | 27 | final _router = GoRouter( 28 | routes: [ 29 | ShellRoute( 30 | path: '/', 31 | defaultRoute: ListenNowFeature.route.path, 32 | builder: (context, child) => AppScaffold(child: child), 33 | routes: [ 34 | ...features.map((f) => f.route), 35 | ], 36 | ), 37 | ], 38 | ); 39 | 40 | @override 41 | Widget build(BuildContext context) { 42 | return MaterialApp.router( 43 | routerDelegate: _router.delegate, 44 | routeInformationParser: _router.parser, 45 | ); 46 | } 47 | } 48 | 49 | class AppScaffold extends StatelessWidget { 50 | final Widget child; 51 | 52 | const AppScaffold({ 53 | required this.child, 54 | Key? key, 55 | }) : super(key: key); 56 | 57 | @override 58 | Widget build(BuildContext context) { 59 | return AdaptiveNavigationScaffold( 60 | body: AnimatedSwitcher( 61 | duration: const Duration(milliseconds: 300), 62 | child: child, 63 | ), 64 | selectedIndex: _selectedIndex(context), 65 | onDestinationSelected: (index) => _changeIndex(context, index), 66 | destinations: [ 67 | ...features.map((f) => f.destination), 68 | ], 69 | ); 70 | } 71 | 72 | int _selectedIndex(BuildContext context) { 73 | final activeChild = RouteState.of(context).activeChild; 74 | if (activeChild == null) { 75 | return 0; 76 | } 77 | return features.indexWhere((feature) => feature.route == activeChild); 78 | } 79 | 80 | void _changeIndex(BuildContext context, int index) { 81 | RouteState.of(context).goTo(features[index].route.path); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /example/lib/feature_splitting/radio.dart: -------------------------------------------------------------------------------- 1 | import 'package:adaptive_navigation/adaptive_navigation.dart'; 2 | import 'package:example/feature_splitting/song.dart'; 3 | import 'package:flutter/material.dart'; 4 | import 'package:go_router_prototype/go_router_prototype.dart'; 5 | 6 | class RadioFeature extends StatelessWidget { 7 | static RouteBase route = NestedStackRoute( 8 | path: 'radio', 9 | builder: (context) => const RadioFeature(), 10 | routes: [ 11 | StackedRoute( 12 | path: 'song/:songId', 13 | builder: (context) => const SongScreen(), 14 | ), 15 | ], 16 | ); 17 | 18 | static const destination = AdaptiveScaffoldDestination( 19 | title: 'Radio', 20 | icon: Icons.radio, 21 | ); 22 | 23 | const RadioFeature({Key? key}) : super(key: key); 24 | 25 | @override 26 | Widget build(BuildContext context) { 27 | return Center( 28 | child: Column( 29 | children: [ 30 | Text( 31 | 'Radio', 32 | style: Theme.of(context).textTheme.headline5, 33 | ), 34 | TextButton( 35 | onPressed: () { 36 | RouteState.of(context).goTo('song/123'); 37 | }, 38 | child: const Text('View song 123'), 39 | ), 40 | ], 41 | ), 42 | ); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /example/lib/feature_splitting/song.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:go_router_prototype/go_router_prototype.dart'; 3 | 4 | class SongScreen extends StatelessWidget { 5 | const SongScreen({Key? key}) : super(key: key); 6 | 7 | @override 8 | Widget build(BuildContext context) { 9 | final songId = RouteState.of(context).pathParameters['songId']; 10 | return Scaffold( 11 | appBar: AppBar(), 12 | body: Center( 13 | child: Text('Song $songId'), 14 | ), 15 | ); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /example/lib/links.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:go_router_prototype/go_router_prototype.dart'; 3 | import 'package:url_launcher/link.dart'; 4 | 5 | void main() { 6 | runApp(LinkWidgetDemo()); 7 | } 8 | 9 | class LinkWidgetDemo extends StatelessWidget { 10 | LinkWidgetDemo({Key? key}) : super(key: key); 11 | 12 | final _router = GoRouter( 13 | routes: [ 14 | StackedRoute( 15 | path: '/', 16 | builder: (context) => const HomeScreen(), 17 | routes: [ 18 | StackedRoute( 19 | path: 'a', 20 | builder: (context) => const AScreen(), 21 | routes: [ 22 | StackedRoute( 23 | path: 'b', 24 | builder: (context) => const BScreen(), 25 | ), 26 | ], 27 | ), 28 | ], 29 | ), 30 | ], 31 | ); 32 | 33 | @override 34 | Widget build(BuildContext context) { 35 | return MaterialApp.router( 36 | routerDelegate: _router.delegate, 37 | routeInformationParser: _router.parser, 38 | ); 39 | } 40 | } 41 | 42 | class HomeScreen extends StatelessWidget { 43 | const HomeScreen({Key? key}) : super(key: key); 44 | 45 | @override 46 | Widget build(BuildContext context) { 47 | return Scaffold( 48 | body: Center( 49 | child: Column( 50 | mainAxisAlignment: MainAxisAlignment.center, 51 | children: [ 52 | const Text('HomeScreen'), 53 | Link( 54 | uri: Uri.parse('/a'), 55 | builder: (context, followLink) { 56 | return TextButton( 57 | child: const Text('Go to A'), 58 | onPressed: followLink, 59 | ); 60 | }, 61 | ), 62 | // TextButton(onPressed: () {}, child: ) 63 | ], 64 | ), 65 | ), 66 | ); 67 | } 68 | } 69 | 70 | class AScreen extends StatelessWidget { 71 | const AScreen({Key? key}) : super(key: key); 72 | 73 | @override 74 | Widget build(BuildContext context) { 75 | return Scaffold( 76 | body: Center( 77 | child: Column( 78 | mainAxisAlignment: MainAxisAlignment.center, 79 | children: [ 80 | const Text('Screen A'), 81 | Link( 82 | uri: Uri.parse('/a/b'), 83 | builder: (context, followLink) { 84 | return TextButton( 85 | child: const Text('Go to B'), 86 | onPressed: followLink, 87 | ); 88 | }, 89 | ), 90 | // TextButton(onPressed: () {}, child: ) 91 | ], 92 | ), 93 | ), 94 | ); 95 | } 96 | } 97 | 98 | class BScreen extends StatelessWidget { 99 | const BScreen({Key? key}) : super(key: key); 100 | 101 | @override 102 | Widget build(BuildContext context) { 103 | return Scaffold( 104 | body: Center( 105 | child: Column( 106 | mainAxisAlignment: MainAxisAlignment.center, 107 | children: [ 108 | const Text('Screen B'), 109 | Link( 110 | uri: Uri.parse('/'), 111 | builder: (context, followLink) { 112 | return TextButton( 113 | child: const Text('Go to /'), 114 | onPressed: followLink, 115 | ); 116 | }, 117 | ), 118 | // TextButton(onPressed: () {}, child: ) 119 | ], 120 | ), 121 | ), 122 | ); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /example/lib/path_parameters.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/go_router_prototype.dart'; 7 | 8 | void main() { 9 | runApp(PathParametersDemo()); 10 | } 11 | 12 | class PathParametersDemo extends StatelessWidget { 13 | PathParametersDemo({Key? key}) : super(key: key); 14 | 15 | static String _userId(BuildContext context) { 16 | final routeState = RouteState.of(context); 17 | final params = routeState.pathParameters; 18 | if (!params.containsKey('id')) { 19 | throw ('Expected :id param in URL'); 20 | } 21 | return params['id']!; 22 | } 23 | 24 | final _router = GoRouter( 25 | routes: [ 26 | StackedRoute( 27 | path: '/', 28 | builder: (context) => const HomeScreen(), 29 | routes: [ 30 | StackedRoute( 31 | path: 'user/:id', 32 | builder: (context) { 33 | return UserScreen(userId: _userId(context)); 34 | }, 35 | routes: [ 36 | StackedRoute( 37 | path: 'details', 38 | builder: (context) { 39 | return UserDetailsScreen(userId: _userId(context)); 40 | }, 41 | ), 42 | ], 43 | ), 44 | ], 45 | ), 46 | ], 47 | ); 48 | 49 | @override 50 | Widget build(BuildContext context) { 51 | return MaterialApp.router( 52 | routerDelegate: _router.delegate, 53 | routeInformationParser: _router.parser, 54 | ); 55 | } 56 | } 57 | 58 | class HomeScreen extends StatelessWidget { 59 | const HomeScreen({Key? key}) : super(key: key); 60 | 61 | @override 62 | Widget build(BuildContext context) { 63 | return Scaffold( 64 | appBar: AppBar( 65 | title: const Text('Basics'), 66 | ), 67 | body: Center( 68 | child: Column( 69 | mainAxisAlignment: MainAxisAlignment.center, 70 | children: [ 71 | Text( 72 | 'Home', 73 | style: Theme.of(context).textTheme.headline4, 74 | ), 75 | TextButton( 76 | child: const Text('User 1'), 77 | onPressed: () { 78 | RouteState.of(context).goTo('/user/1'); 79 | }, 80 | ), 81 | TextButton( 82 | child: const Text('User 2'), 83 | onPressed: () { 84 | RouteState.of(context).goTo('/user/2'); 85 | }, 86 | ), 87 | TextButton( 88 | child: const Text('User abc'), 89 | onPressed: () { 90 | RouteState.of(context).goTo('/user/abc'); 91 | }, 92 | ), 93 | ], 94 | ), 95 | ), 96 | ); 97 | } 98 | } 99 | 100 | class UserScreen extends StatelessWidget { 101 | final String userId; 102 | 103 | const UserScreen({ 104 | required this.userId, 105 | Key? key, 106 | }) : super(key: key); 107 | 108 | @override 109 | Widget build(BuildContext context) { 110 | return Scaffold( 111 | appBar: AppBar( 112 | title: Text('User $userId'), 113 | ), 114 | body: Center( 115 | child: Column( 116 | mainAxisAlignment: MainAxisAlignment.center, 117 | children: [ 118 | Text( 119 | 'User $userId', 120 | style: Theme.of(context).textTheme.headline4, 121 | ), 122 | TextButton( 123 | onPressed: () { 124 | RouteState.of(context).goTo('details'); 125 | }, 126 | child: const Text('View details'), 127 | ), 128 | ], 129 | ), 130 | ), 131 | ); 132 | } 133 | } 134 | 135 | class UserDetailsScreen extends StatelessWidget { 136 | final String userId; 137 | 138 | const UserDetailsScreen({ 139 | required this.userId, 140 | Key? key, 141 | }) : super(key: key); 142 | 143 | @override 144 | Widget build(BuildContext context) { 145 | return Scaffold( 146 | appBar: AppBar( 147 | title: const Text('Details'), 148 | ), 149 | body: Center( 150 | child: Column( 151 | mainAxisAlignment: MainAxisAlignment.center, 152 | children: [ 153 | Text( 154 | 'Details for user $userId', 155 | style: Theme.of(context).textTheme.headline4, 156 | ), 157 | ], 158 | ), 159 | ), 160 | ); 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /example/lib/recursive_shell.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/go_router_prototype.dart'; 7 | 8 | void main() { 9 | runApp(ShellDemo()); 10 | } 11 | 12 | Map routeMap = { 13 | 'Desktop': { 14 | 'file1.txt': {}, 15 | 'file2.txt': {}, 16 | 'file3.txt': {}, 17 | }, 18 | 'Documents': { 19 | 'Books': { 20 | 'Left Hand of Darkness': {}, 21 | 'Kindred': {}, 22 | }, 23 | 'Movies': { 24 | 'Batman Begins': {}, 25 | 'The Dark Knight': {}, 26 | 'The Dark Knight Rises': {}, 27 | }, 28 | 'Music': { 29 | 'Playlists': { 30 | '2022': {}, 31 | '2021': {}, 32 | '2020': {}, 33 | '2019': {}, 34 | }, 35 | 'Artists': {}, 36 | 'Songs': {}, 37 | }, 38 | 'Pictures': {}, 39 | }, 40 | }; 41 | 42 | List _buildRoutesRecursive(Map routeMap) { 43 | final children = []; 44 | for (var key in routeMap.keys) { 45 | final childMap = routeMap[key] as Map; 46 | children.add( 47 | ShellRoute( 48 | path: key, 49 | builder: (context, child) { 50 | return RouteList( 51 | child: child, 52 | childPaths: [...childMap.keys], 53 | ); 54 | }, 55 | routes: _buildRoutesRecursive(childMap), 56 | ), 57 | ); 58 | } 59 | return children; 60 | } 61 | 62 | class ShellDemo extends StatelessWidget { 63 | ShellDemo({Key? key}) : super(key: key); 64 | 65 | final _router = GoRouter( 66 | routes: [ 67 | ShellRoute( 68 | path: '/', 69 | builder: (context, child) { 70 | return AppScaffold( 71 | childPaths: [...routeMap.keys], 72 | child: child, 73 | ); 74 | }, 75 | routes: _buildRoutesRecursive(routeMap), 76 | ), 77 | ], 78 | ); 79 | 80 | @override 81 | Widget build(BuildContext context) { 82 | return MaterialApp.router( 83 | routerDelegate: _router.delegate, 84 | routeInformationParser: _router.parser, 85 | ); 86 | } 87 | } 88 | 89 | class AppScaffold extends StatefulWidget { 90 | final Widget child; 91 | final List childPaths; 92 | 93 | const AppScaffold({required this.childPaths, required this.child, Key? key}) 94 | : super(key: key); 95 | 96 | @override 97 | State createState() => _AppScaffoldState(); 98 | } 99 | 100 | class _AppScaffoldState extends State { 101 | final ScrollController _scrollController = ScrollController(); 102 | 103 | @override 104 | Widget build(BuildContext context) { 105 | return Scaffold( 106 | body: SafeArea( 107 | child: Scrollbar( 108 | thumbVisibility: true, 109 | controller: _scrollController, 110 | child: LayoutBuilder( 111 | builder: (context, viewportConstraints) { 112 | return SingleChildScrollView( 113 | scrollDirection: Axis.horizontal, 114 | controller: _scrollController, 115 | child: RouteList( 116 | childPaths: widget.childPaths, 117 | child: widget.child, 118 | ), 119 | ); 120 | }, 121 | ), 122 | ), 123 | ), 124 | ); 125 | } 126 | } 127 | 128 | class RouteList extends StatelessWidget { 129 | final Widget child; 130 | final List childPaths; 131 | 132 | const RouteList({required this.child, required this.childPaths, Key? key}) 133 | : super(key: key); 134 | 135 | @override 136 | Widget build(BuildContext context) { 137 | return Row( 138 | mainAxisSize: MainAxisSize.min, 139 | children: [ 140 | Container( 141 | decoration: BoxDecoration( 142 | border: Border( 143 | right: BorderSide(width: 1, color: Colors.grey[400]!), 144 | ), 145 | ), 146 | constraints: const BoxConstraints.tightFor(width: 256), 147 | child: RouteSelector( 148 | childPaths: childPaths, 149 | ), 150 | ), 151 | child, 152 | ], 153 | ); 154 | } 155 | } 156 | 157 | class RouteSelector extends StatelessWidget { 158 | final List childPaths; 159 | 160 | const RouteSelector({required this.childPaths, Key? key}) : super(key: key); 161 | 162 | @override 163 | Widget build(BuildContext context) { 164 | return Column( 165 | children: [ 166 | ...childPaths.map( 167 | (p) => ListTile( 168 | onTap: () { 169 | RouteState.of(context).goTo(p); 170 | }, 171 | selected: RouteState.of(context).activeChild?.path == p, 172 | title: Text(p), 173 | ), 174 | ), 175 | ], 176 | ); 177 | } 178 | } 179 | 180 | class BScreen extends StatelessWidget { 181 | const BScreen({Key? key}) : super(key: key); 182 | 183 | @override 184 | Widget build(BuildContext context) { 185 | return const Text('Screen B'); 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /example/lib/sign_in.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2021, the Flutter project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Sign-in example 6 | /// Done using go_router 7 | 8 | import 'package:flutter/material.dart'; 9 | import 'package:go_router_prototype/go_router_prototype.dart'; 10 | 11 | void main() { 12 | runApp(const BooksApp()); 13 | } 14 | 15 | class Credentials { 16 | final String username; 17 | final String password; 18 | 19 | Credentials(this.username, this.password); 20 | } 21 | 22 | class Authentication extends ChangeNotifier { 23 | bool _signedIn = false; 24 | 25 | bool isSignedIn() => _signedIn; 26 | 27 | Future signOut() async { 28 | _signedIn = false; 29 | notifyListeners(); 30 | } 31 | 32 | Future signIn(String username, String password) async { 33 | _signedIn = true; 34 | notifyListeners(); 35 | return true; 36 | } 37 | } 38 | 39 | class BooksApp extends StatefulWidget { 40 | const BooksApp({Key? key}) : super(key: key); 41 | 42 | @override 43 | State createState() => _BooksAppState(); 44 | } 45 | 46 | class AppState { 47 | final Authentication auth; 48 | 49 | AppState(this.auth); 50 | 51 | Future signIn(String username, String password) async { 52 | var success = await auth.signIn(username, password); 53 | return success; 54 | } 55 | 56 | Future signOut() async { 57 | await auth.signOut(); 58 | } 59 | } 60 | 61 | class _BooksAppState extends State { 62 | final AppState _appState = AppState(Authentication()); 63 | 64 | @override 65 | Widget build(BuildContext context) { 66 | return MaterialApp.router( 67 | routeInformationParser: _router.parser, 68 | routerDelegate: _router.delegate, 69 | ); 70 | } 71 | 72 | late final _router = GoRouter( 73 | refreshListenable: _appState.auth, 74 | routes: [ 75 | ShellRoute( 76 | path: '/', 77 | builder: (context, child) => child, 78 | redirect: (state) async { 79 | final signedIn = _appState.auth.isSignedIn(); 80 | if (!signedIn) return '/signin'; 81 | return null; 82 | }, 83 | routes: [ 84 | StackedRoute( 85 | path: 'home', 86 | builder: (context) => HomeScreen( 87 | onSignOut: () async { 88 | await _appState.signOut(); 89 | }, 90 | ), 91 | routes: [ 92 | StackedRoute( 93 | path: 'books', 94 | builder: (context) => const BooksListScreen(), 95 | ), 96 | ], 97 | ), 98 | StackedRoute( 99 | path: 'signin', 100 | builder: (context) => SignInScreen( 101 | onSignedIn: (credentials) async { 102 | await _appState.signIn( 103 | credentials.username, credentials.password); 104 | RouteState.of(context).goTo('/home'); 105 | }, 106 | ), 107 | ), 108 | ], 109 | ), 110 | ], 111 | ); 112 | } 113 | 114 | class HomeScreen extends StatelessWidget { 115 | final VoidCallback onSignOut; 116 | 117 | const HomeScreen({required this.onSignOut, Key? key}) : super(key: key); 118 | 119 | @override 120 | Widget build(BuildContext context) { 121 | return Scaffold( 122 | appBar: AppBar(), 123 | body: Center( 124 | child: Column( 125 | children: [ 126 | ElevatedButton( 127 | onPressed: () => RouteState.of(context).goTo('books'), 128 | child: const Text('View my bookshelf'), 129 | ), 130 | ElevatedButton( 131 | onPressed: onSignOut, 132 | child: const Text('Sign out'), 133 | ), 134 | ], 135 | ), 136 | ), 137 | ); 138 | } 139 | } 140 | 141 | class SignInScreen extends StatefulWidget { 142 | final ValueChanged onSignedIn; 143 | 144 | const SignInScreen({required this.onSignedIn, Key? key}) : super(key: key); 145 | 146 | @override 147 | _SignInScreenState createState() => _SignInScreenState(); 148 | } 149 | 150 | class _SignInScreenState extends State { 151 | String _username = ''; 152 | String _password = ''; 153 | 154 | @override 155 | Widget build(BuildContext context) { 156 | return Scaffold( 157 | appBar: AppBar(), 158 | body: Center( 159 | child: Column( 160 | children: [ 161 | TextField( 162 | decoration: const InputDecoration(hintText: 'username (any)'), 163 | onChanged: (s) => _username = s, 164 | ), 165 | TextField( 166 | decoration: const InputDecoration(hintText: 'password (any)'), 167 | obscureText: true, 168 | onChanged: (s) => _password = s, 169 | ), 170 | ElevatedButton( 171 | onPressed: () => 172 | widget.onSignedIn(Credentials(_username, _password)), 173 | child: const Text('Sign in'), 174 | ), 175 | ], 176 | ), 177 | ), 178 | ); 179 | } 180 | } 181 | 182 | class BooksListScreen extends StatelessWidget { 183 | const BooksListScreen({Key? key}) : super(key: key); 184 | 185 | @override 186 | Widget build(BuildContext context) { 187 | return Scaffold( 188 | appBar: AppBar(), 189 | body: ListView( 190 | children: const [ 191 | ListTile( 192 | title: Text('Stranger in a Strange Land'), 193 | subtitle: Text('Robert A. Heinlein'), 194 | ), 195 | ListTile( 196 | title: Text('Foundation'), 197 | subtitle: Text('Isaac Asimov'), 198 | ), 199 | ListTile( 200 | title: Text('Fahrenheit 451'), 201 | subtitle: Text('Ray Bradbury'), 202 | ), 203 | ], 204 | ), 205 | ); 206 | } 207 | } 208 | 209 | class ErrorScreen extends StatelessWidget { 210 | const ErrorScreen(this.error, {Key? key}) : super(key: key); 211 | final Exception? error; 212 | 213 | @override 214 | Widget build(BuildContext context) => Scaffold( 215 | appBar: AppBar(title: const Text('Page Not Found')), 216 | body: Center( 217 | child: Column( 218 | mainAxisAlignment: MainAxisAlignment.center, 219 | children: [ 220 | Text(error?.toString() ?? 'page not found'), 221 | TextButton( 222 | onPressed: () => RouteState.of(context).goTo('/'), 223 | child: const Text('Home'), 224 | ), 225 | ], 226 | ), 227 | ), 228 | ); 229 | } 230 | -------------------------------------------------------------------------------- /example/lib/stacked_nested_nav.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/go_router_prototype.dart'; 7 | 8 | void main() { 9 | runApp(BottomNavigationBarDemo()); 10 | } 11 | 12 | class BottomNavigationBarDemo extends StatelessWidget { 13 | BottomNavigationBarDemo({Key? key}) : super(key: key); 14 | 15 | final _router = GoRouter( 16 | routes: [ 17 | StackedRoute( 18 | path: '/', 19 | builder: (context) => const HomeScreen(), 20 | routes: [ 21 | ShellRoute( 22 | path: 'a', 23 | builder: (context, child) => AScreen(child: child), 24 | routes: [ 25 | NestedStackRoute( 26 | path: 'b', 27 | builder: (context) => const BScreen(), 28 | routes: [ 29 | StackedRoute( 30 | path: 'c', 31 | builder: (context) => const CScreen(), 32 | ), 33 | ], 34 | ), 35 | ], 36 | ), 37 | ], 38 | ), 39 | ], 40 | ); 41 | 42 | @override 43 | Widget build(BuildContext context) { 44 | return MaterialApp.router( 45 | routerDelegate: _router.delegate, 46 | routeInformationParser: _router.parser, 47 | ); 48 | } 49 | } 50 | 51 | class HomeScreen extends StatelessWidget { 52 | const HomeScreen({Key? key}) : super(key: key); 53 | 54 | @override 55 | Widget build(BuildContext context) { 56 | return Scaffold( 57 | appBar: AppBar(title: const Text('Home')), 58 | body: Center( 59 | child: Column( 60 | children: [ 61 | const Text('Home'), 62 | TextButton( 63 | onPressed: () { 64 | RouteState.of(context).goTo('a'); 65 | }, 66 | child: const Text('Go to A'), 67 | ), 68 | ], 69 | ), 70 | ), 71 | ); 72 | } 73 | } 74 | 75 | class AScreen extends StatelessWidget { 76 | final Widget child; 77 | 78 | const AScreen({required this.child, Key? key}) : super(key: key); 79 | 80 | @override 81 | Widget build(BuildContext context) { 82 | return Scaffold( 83 | appBar: AppBar(title: const Text('Screen A')), 84 | body: Center( 85 | child: Column( 86 | children: [ 87 | const Text('Screen A'), 88 | TextButton( 89 | onPressed: () { 90 | RouteState.of(context).goTo('b'); 91 | }, 92 | child: const Text('Go to B'), 93 | ), 94 | Expanded(child: child), 95 | ], 96 | ), 97 | ), 98 | ); 99 | } 100 | } 101 | 102 | class BScreen extends StatelessWidget { 103 | const BScreen({Key? key}) : super(key: key); 104 | 105 | @override 106 | Widget build(BuildContext context) { 107 | return Scaffold( 108 | appBar: AppBar( 109 | title: const Text('Screen B'), 110 | ), 111 | body: Center( 112 | child: Column( 113 | children: [ 114 | const Text('Screen B'), 115 | TextButton( 116 | onPressed: () { 117 | RouteState.of(context).goTo('c'); 118 | }, 119 | child: const Text('Go to C'), 120 | ), 121 | ], 122 | ), 123 | ), 124 | ); 125 | } 126 | } 127 | 128 | class CScreen extends StatelessWidget { 129 | const CScreen({Key? key}) : super(key: key); 130 | 131 | @override 132 | Widget build(BuildContext context) { 133 | return Scaffold( 134 | appBar: AppBar( 135 | title: const Text('Screen C'), 136 | ), 137 | body: Center( 138 | child: Column( 139 | children: [ 140 | const Text('Screen B'), 141 | TextButton( 142 | onPressed: () { 143 | RouteState.of(context).goTo('/'); 144 | }, 145 | child: const Text('Go to /'), 146 | ), 147 | ], 148 | ), 149 | ), 150 | ); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /example/lib/url_strategy.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:flutter_web_plugins/url_strategy.dart'; 7 | 8 | import 'path_parameters.dart'; 9 | 10 | void main() { 11 | usePathUrlStrategy(); 12 | runApp(PathParametersDemo()); 13 | } 14 | -------------------------------------------------------------------------------- /example/pubspec.lock: -------------------------------------------------------------------------------- 1 | # Generated by pub 2 | # See https://dart.dev/tools/pub/glossary#lockfile 3 | packages: 4 | adaptive_breakpoints: 5 | dependency: transitive 6 | description: 7 | name: adaptive_breakpoints 8 | url: "https://pub.dartlang.org" 9 | source: hosted 10 | version: "0.0.5" 11 | adaptive_navigation: 12 | dependency: "direct main" 13 | description: 14 | name: adaptive_navigation 15 | url: "https://pub.dartlang.org" 16 | source: hosted 17 | version: "0.0.5" 18 | async: 19 | dependency: transitive 20 | description: 21 | name: async 22 | url: "https://pub.dartlang.org" 23 | source: hosted 24 | version: "2.8.2" 25 | boolean_selector: 26 | dependency: transitive 27 | description: 28 | name: boolean_selector 29 | url: "https://pub.dartlang.org" 30 | source: hosted 31 | version: "2.1.0" 32 | characters: 33 | dependency: transitive 34 | description: 35 | name: characters 36 | url: "https://pub.dartlang.org" 37 | source: hosted 38 | version: "1.2.0" 39 | charcode: 40 | dependency: transitive 41 | description: 42 | name: charcode 43 | url: "https://pub.dartlang.org" 44 | source: hosted 45 | version: "1.3.1" 46 | clock: 47 | dependency: transitive 48 | description: 49 | name: clock 50 | url: "https://pub.dartlang.org" 51 | source: hosted 52 | version: "1.1.0" 53 | collection: 54 | dependency: transitive 55 | description: 56 | name: collection 57 | url: "https://pub.dartlang.org" 58 | source: hosted 59 | version: "1.16.0" 60 | cupertino_icons: 61 | dependency: "direct main" 62 | description: 63 | name: cupertino_icons 64 | url: "https://pub.dartlang.org" 65 | source: hosted 66 | version: "1.0.4" 67 | fake_async: 68 | dependency: transitive 69 | description: 70 | name: fake_async 71 | url: "https://pub.dartlang.org" 72 | source: hosted 73 | version: "1.3.0" 74 | flutter: 75 | dependency: "direct main" 76 | description: flutter 77 | source: sdk 78 | version: "0.0.0" 79 | flutter_lints: 80 | dependency: "direct dev" 81 | description: 82 | name: flutter_lints 83 | url: "https://pub.dartlang.org" 84 | source: hosted 85 | version: "1.0.4" 86 | flutter_test: 87 | dependency: "direct dev" 88 | description: flutter 89 | source: sdk 90 | version: "0.0.0" 91 | flutter_web_plugins: 92 | dependency: "direct main" 93 | description: flutter 94 | source: sdk 95 | version: "0.0.0" 96 | go_router_prototype: 97 | dependency: "direct main" 98 | description: 99 | path: ".." 100 | relative: true 101 | source: path 102 | version: "0.0.1" 103 | js: 104 | dependency: transitive 105 | description: 106 | name: js 107 | url: "https://pub.dartlang.org" 108 | source: hosted 109 | version: "0.6.4" 110 | lints: 111 | dependency: transitive 112 | description: 113 | name: lints 114 | url: "https://pub.dartlang.org" 115 | source: hosted 116 | version: "1.0.1" 117 | matcher: 118 | dependency: transitive 119 | description: 120 | name: matcher 121 | url: "https://pub.dartlang.org" 122 | source: hosted 123 | version: "0.12.11" 124 | material_color_utilities: 125 | dependency: transitive 126 | description: 127 | name: material_color_utilities 128 | url: "https://pub.dartlang.org" 129 | source: hosted 130 | version: "0.1.4" 131 | meta: 132 | dependency: transitive 133 | description: 134 | name: meta 135 | url: "https://pub.dartlang.org" 136 | source: hosted 137 | version: "1.7.0" 138 | path: 139 | dependency: transitive 140 | description: 141 | name: path 142 | url: "https://pub.dartlang.org" 143 | source: hosted 144 | version: "1.8.1" 145 | path_to_regexp: 146 | dependency: transitive 147 | description: 148 | name: path_to_regexp 149 | url: "https://pub.dartlang.org" 150 | source: hosted 151 | version: "0.4.0" 152 | plugin_platform_interface: 153 | dependency: transitive 154 | description: 155 | name: plugin_platform_interface 156 | url: "https://pub.dartlang.org" 157 | source: hosted 158 | version: "2.1.2" 159 | quiver: 160 | dependency: transitive 161 | description: 162 | name: quiver 163 | url: "https://pub.dartlang.org" 164 | source: hosted 165 | version: "3.0.1+1" 166 | sky_engine: 167 | dependency: transitive 168 | description: flutter 169 | source: sdk 170 | version: "0.0.99" 171 | source_span: 172 | dependency: transitive 173 | description: 174 | name: source_span 175 | url: "https://pub.dartlang.org" 176 | source: hosted 177 | version: "1.8.2" 178 | stack_trace: 179 | dependency: transitive 180 | description: 181 | name: stack_trace 182 | url: "https://pub.dartlang.org" 183 | source: hosted 184 | version: "1.10.0" 185 | stream_channel: 186 | dependency: transitive 187 | description: 188 | name: stream_channel 189 | url: "https://pub.dartlang.org" 190 | source: hosted 191 | version: "2.1.0" 192 | string_scanner: 193 | dependency: transitive 194 | description: 195 | name: string_scanner 196 | url: "https://pub.dartlang.org" 197 | source: hosted 198 | version: "1.1.0" 199 | term_glyph: 200 | dependency: transitive 201 | description: 202 | name: term_glyph 203 | url: "https://pub.dartlang.org" 204 | source: hosted 205 | version: "1.2.0" 206 | test_api: 207 | dependency: transitive 208 | description: 209 | name: test_api 210 | url: "https://pub.dartlang.org" 211 | source: hosted 212 | version: "0.4.9" 213 | url_launcher: 214 | dependency: "direct main" 215 | description: 216 | name: url_launcher 217 | url: "https://pub.dartlang.org" 218 | source: hosted 219 | version: "6.0.20" 220 | url_launcher_android: 221 | dependency: transitive 222 | description: 223 | name: url_launcher_android 224 | url: "https://pub.dartlang.org" 225 | source: hosted 226 | version: "6.0.15" 227 | url_launcher_ios: 228 | dependency: transitive 229 | description: 230 | name: url_launcher_ios 231 | url: "https://pub.dartlang.org" 232 | source: hosted 233 | version: "6.0.15" 234 | url_launcher_linux: 235 | dependency: transitive 236 | description: 237 | name: url_launcher_linux 238 | url: "https://pub.dartlang.org" 239 | source: hosted 240 | version: "3.0.0" 241 | url_launcher_macos: 242 | dependency: transitive 243 | description: 244 | name: url_launcher_macos 245 | url: "https://pub.dartlang.org" 246 | source: hosted 247 | version: "3.0.0" 248 | url_launcher_platform_interface: 249 | dependency: transitive 250 | description: 251 | name: url_launcher_platform_interface 252 | url: "https://pub.dartlang.org" 253 | source: hosted 254 | version: "2.0.5" 255 | url_launcher_web: 256 | dependency: transitive 257 | description: 258 | name: url_launcher_web 259 | url: "https://pub.dartlang.org" 260 | source: hosted 261 | version: "2.0.9" 262 | url_launcher_windows: 263 | dependency: transitive 264 | description: 265 | name: url_launcher_windows 266 | url: "https://pub.dartlang.org" 267 | source: hosted 268 | version: "3.0.0" 269 | vector_math: 270 | dependency: transitive 271 | description: 272 | name: vector_math 273 | url: "https://pub.dartlang.org" 274 | source: hosted 275 | version: "2.1.2" 276 | sdks: 277 | dart: ">=2.17.0-0 <3.0.0" 278 | flutter: ">=2.10.0" 279 | -------------------------------------------------------------------------------- /example/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: example 2 | description: A new Flutter project. 3 | publish_to: 'none' # Remove this line if you wish to publish to pub.dev 4 | version: 1.0.0+1 5 | environment: 6 | sdk: ">=2.16.1 <3.0.0" 7 | dependencies: 8 | flutter: 9 | sdk: flutter 10 | flutter_web_plugins: 11 | sdk: flutter 12 | cupertino_icons: ^1.0.2 13 | go_router_prototype: 14 | path: ../ 15 | url_launcher: ^6.0.0 16 | adaptive_navigation: ^0.0.5 17 | dev_dependencies: 18 | flutter_test: 19 | sdk: flutter 20 | flutter_lints: ^1.0.0 21 | flutter: 22 | uses-material-design: true 23 | -------------------------------------------------------------------------------- /example/web/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/web/favicon.png -------------------------------------------------------------------------------- /example/web/icons/Icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/web/icons/Icon-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/web/icons/Icon-512.png -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/web/icons/Icon-maskable-192.png -------------------------------------------------------------------------------- /example/web/icons/Icon-maskable-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/web/icons/Icon-maskable-512.png -------------------------------------------------------------------------------- /example/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | example 33 | 34 | 35 | 36 | 39 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /example/web/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "short_name": "example", 4 | "start_url": ".", 5 | "display": "standalone", 6 | "background_color": "#0175C2", 7 | "theme_color": "#0175C2", 8 | "description": "A new Flutter project.", 9 | "orientation": "portrait-primary", 10 | "prefer_related_applications": false, 11 | "icons": [ 12 | { 13 | "src": "icons/Icon-192.png", 14 | "sizes": "192x192", 15 | "type": "image/png" 16 | }, 17 | { 18 | "src": "icons/Icon-512.png", 19 | "sizes": "512x512", 20 | "type": "image/png" 21 | }, 22 | { 23 | "src": "icons/Icon-maskable-192.png", 24 | "sizes": "192x192", 25 | "type": "image/png", 26 | "purpose": "maskable" 27 | }, 28 | { 29 | "src": "icons/Icon-maskable-512.png", 30 | "sizes": "512x512", 31 | "type": "image/png", 32 | "purpose": "maskable" 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /example/windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /example/windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(example LANGUAGES CXX) 3 | 4 | set(BINARY_NAME "example") 5 | 6 | cmake_policy(SET CMP0063 NEW) 7 | 8 | set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") 9 | 10 | # Configure build options. 11 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) 12 | if(IS_MULTICONFIG) 13 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" 14 | CACHE STRING "" FORCE) 15 | else() 16 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 17 | set(CMAKE_BUILD_TYPE "Debug" CACHE 18 | STRING "Flutter build mode" FORCE) 19 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 20 | "Debug" "Profile" "Release") 21 | endif() 22 | endif() 23 | 24 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") 25 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") 26 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") 27 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") 28 | 29 | # Use Unicode for all projects. 30 | add_definitions(-DUNICODE -D_UNICODE) 31 | 32 | # Compilation settings that should be applied to most targets. 33 | function(APPLY_STANDARD_SETTINGS TARGET) 34 | target_compile_features(${TARGET} PUBLIC cxx_std_17) 35 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") 36 | target_compile_options(${TARGET} PRIVATE /EHsc) 37 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") 38 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") 39 | endfunction() 40 | 41 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 42 | 43 | # Flutter library and tool build rules. 44 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 45 | 46 | # Application build 47 | add_subdirectory("runner") 48 | 49 | # Generated plugin build rules, which manage building the plugins and adding 50 | # them to the application. 51 | include(flutter/generated_plugins.cmake) 52 | 53 | 54 | # === Installation === 55 | # Support files are copied into place next to the executable, so that it can 56 | # run in place. This is done instead of making a separate bundle (as on Linux) 57 | # so that building and running from within Visual Studio will work. 58 | set(BUILD_BUNDLE_DIR "$") 59 | # Make the "install" step default, as it's required to run. 60 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) 61 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 62 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 63 | endif() 64 | 65 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 66 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") 67 | 68 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 69 | COMPONENT Runtime) 70 | 71 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 72 | COMPONENT Runtime) 73 | 74 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 75 | COMPONENT Runtime) 76 | 77 | if(PLUGIN_BUNDLED_LIBRARIES) 78 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" 79 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 80 | COMPONENT Runtime) 81 | endif() 82 | 83 | # Fully re-copy the assets directory on each build to avoid having stale files 84 | # from a previous install. 85 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 86 | install(CODE " 87 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 88 | " COMPONENT Runtime) 89 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 90 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 91 | 92 | # Install the AOT library on non-Debug builds only. 93 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 94 | CONFIGURATIONS Profile;Release 95 | COMPONENT Runtime) 96 | -------------------------------------------------------------------------------- /example/windows/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | 3 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 4 | 5 | # Configuration provided via flutter tool. 6 | include(${EPHEMERAL_DIR}/generated_config.cmake) 7 | 8 | # TODO: Move the rest of this into files in ephemeral. See 9 | # https://github.com/flutter/flutter/issues/57146. 10 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") 11 | 12 | # === Flutter Library === 13 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") 14 | 15 | # Published to parent scope for install step. 16 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 17 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 18 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 19 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) 20 | 21 | list(APPEND FLUTTER_LIBRARY_HEADERS 22 | "flutter_export.h" 23 | "flutter_windows.h" 24 | "flutter_messenger.h" 25 | "flutter_plugin_registrar.h" 26 | "flutter_texture_registrar.h" 27 | ) 28 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") 29 | add_library(flutter INTERFACE) 30 | target_include_directories(flutter INTERFACE 31 | "${EPHEMERAL_DIR}" 32 | ) 33 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") 34 | add_dependencies(flutter flutter_assemble) 35 | 36 | # === Wrapper === 37 | list(APPEND CPP_WRAPPER_SOURCES_CORE 38 | "core_implementations.cc" 39 | "standard_codec.cc" 40 | ) 41 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") 42 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN 43 | "plugin_registrar.cc" 44 | ) 45 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") 46 | list(APPEND CPP_WRAPPER_SOURCES_APP 47 | "flutter_engine.cc" 48 | "flutter_view_controller.cc" 49 | ) 50 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") 51 | 52 | # Wrapper sources needed for a plugin. 53 | add_library(flutter_wrapper_plugin STATIC 54 | ${CPP_WRAPPER_SOURCES_CORE} 55 | ${CPP_WRAPPER_SOURCES_PLUGIN} 56 | ) 57 | apply_standard_settings(flutter_wrapper_plugin) 58 | set_target_properties(flutter_wrapper_plugin PROPERTIES 59 | POSITION_INDEPENDENT_CODE ON) 60 | set_target_properties(flutter_wrapper_plugin PROPERTIES 61 | CXX_VISIBILITY_PRESET hidden) 62 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) 63 | target_include_directories(flutter_wrapper_plugin PUBLIC 64 | "${WRAPPER_ROOT}/include" 65 | ) 66 | add_dependencies(flutter_wrapper_plugin flutter_assemble) 67 | 68 | # Wrapper sources needed for the runner. 69 | add_library(flutter_wrapper_app STATIC 70 | ${CPP_WRAPPER_SOURCES_CORE} 71 | ${CPP_WRAPPER_SOURCES_APP} 72 | ) 73 | apply_standard_settings(flutter_wrapper_app) 74 | target_link_libraries(flutter_wrapper_app PUBLIC flutter) 75 | target_include_directories(flutter_wrapper_app PUBLIC 76 | "${WRAPPER_ROOT}/include" 77 | ) 78 | add_dependencies(flutter_wrapper_app flutter_assemble) 79 | 80 | # === Flutter tool backend === 81 | # _phony_ is a non-existent file to force this command to run every time, 82 | # since currently there's no way to get a full input/output list from the 83 | # flutter tool. 84 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") 85 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) 86 | add_custom_command( 87 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 88 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} 89 | ${CPP_WRAPPER_SOURCES_APP} 90 | ${PHONY_OUTPUT} 91 | COMMAND ${CMAKE_COMMAND} -E env 92 | ${FLUTTER_TOOL_ENVIRONMENT} 93 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" 94 | windows-x64 $ 95 | VERBATIM 96 | ) 97 | add_custom_target(flutter_assemble DEPENDS 98 | "${FLUTTER_LIBRARY}" 99 | ${FLUTTER_LIBRARY_HEADERS} 100 | ${CPP_WRAPPER_SOURCES_CORE} 101 | ${CPP_WRAPPER_SOURCES_PLUGIN} 102 | ${CPP_WRAPPER_SOURCES_APP} 103 | ) 104 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | 10 | void RegisterPlugins(flutter::PluginRegistry* registry) { 11 | } 12 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void RegisterPlugins(flutter::PluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /example/windows/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | ) 7 | 8 | set(PLUGIN_BUNDLED_LIBRARIES) 9 | 10 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 11 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) 12 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 13 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 14 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 15 | endforeach(plugin) 16 | -------------------------------------------------------------------------------- /example/windows/runner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(runner LANGUAGES CXX) 3 | 4 | add_executable(${BINARY_NAME} WIN32 5 | "flutter_window.cpp" 6 | "main.cpp" 7 | "utils.cpp" 8 | "win32_window.cpp" 9 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 10 | "Runner.rc" 11 | "runner.exe.manifest" 12 | ) 13 | apply_standard_settings(${BINARY_NAME}) 14 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") 15 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) 16 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") 17 | add_dependencies(${BINARY_NAME} flutter_assemble) 18 | -------------------------------------------------------------------------------- /example/windows/runner/Runner.rc: -------------------------------------------------------------------------------- 1 | // Microsoft Visual C++ generated resource script. 2 | // 3 | #pragma code_page(65001) 4 | #include "resource.h" 5 | 6 | #define APSTUDIO_READONLY_SYMBOLS 7 | ///////////////////////////////////////////////////////////////////////////// 8 | // 9 | // Generated from the TEXTINCLUDE 2 resource. 10 | // 11 | #include "winres.h" 12 | 13 | ///////////////////////////////////////////////////////////////////////////// 14 | #undef APSTUDIO_READONLY_SYMBOLS 15 | 16 | ///////////////////////////////////////////////////////////////////////////// 17 | // English (United States) resources 18 | 19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) 20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US 21 | 22 | #ifdef APSTUDIO_INVOKED 23 | ///////////////////////////////////////////////////////////////////////////// 24 | // 25 | // TEXTINCLUDE 26 | // 27 | 28 | 1 TEXTINCLUDE 29 | BEGIN 30 | "resource.h\0" 31 | END 32 | 33 | 2 TEXTINCLUDE 34 | BEGIN 35 | "#include ""winres.h""\r\n" 36 | "\0" 37 | END 38 | 39 | 3 TEXTINCLUDE 40 | BEGIN 41 | "\r\n" 42 | "\0" 43 | END 44 | 45 | #endif // APSTUDIO_INVOKED 46 | 47 | 48 | ///////////////////////////////////////////////////////////////////////////// 49 | // 50 | // Icon 51 | // 52 | 53 | // Icon with lowest ID value placed first to ensure application icon 54 | // remains consistent on all systems. 55 | IDI_APP_ICON ICON "resources\\app_icon.ico" 56 | 57 | 58 | ///////////////////////////////////////////////////////////////////////////// 59 | // 60 | // Version 61 | // 62 | 63 | #ifdef FLUTTER_BUILD_NUMBER 64 | #define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER 65 | #else 66 | #define VERSION_AS_NUMBER 1,0,0 67 | #endif 68 | 69 | #ifdef FLUTTER_BUILD_NAME 70 | #define VERSION_AS_STRING #FLUTTER_BUILD_NAME 71 | #else 72 | #define VERSION_AS_STRING "1.0.0" 73 | #endif 74 | 75 | VS_VERSION_INFO VERSIONINFO 76 | FILEVERSION VERSION_AS_NUMBER 77 | PRODUCTVERSION VERSION_AS_NUMBER 78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK 79 | #ifdef _DEBUG 80 | FILEFLAGS VS_FF_DEBUG 81 | #else 82 | FILEFLAGS 0x0L 83 | #endif 84 | FILEOS VOS__WINDOWS32 85 | FILETYPE VFT_APP 86 | FILESUBTYPE 0x0L 87 | BEGIN 88 | BLOCK "StringFileInfo" 89 | BEGIN 90 | BLOCK "040904e4" 91 | BEGIN 92 | VALUE "CompanyName", "com.example" "\0" 93 | VALUE "FileDescription", "example" "\0" 94 | VALUE "FileVersion", VERSION_AS_STRING "\0" 95 | VALUE "InternalName", "example" "\0" 96 | VALUE "LegalCopyright", "Copyright (C) 2022 com.example. All rights reserved." "\0" 97 | VALUE "OriginalFilename", "example.exe" "\0" 98 | VALUE "ProductName", "example" "\0" 99 | VALUE "ProductVersion", VERSION_AS_STRING "\0" 100 | END 101 | END 102 | BLOCK "VarFileInfo" 103 | BEGIN 104 | VALUE "Translation", 0x409, 1252 105 | END 106 | END 107 | 108 | #endif // English (United States) resources 109 | ///////////////////////////////////////////////////////////////////////////// 110 | 111 | 112 | 113 | #ifndef APSTUDIO_INVOKED 114 | ///////////////////////////////////////////////////////////////////////////// 115 | // 116 | // Generated from the TEXTINCLUDE 3 resource. 117 | // 118 | 119 | 120 | ///////////////////////////////////////////////////////////////////////////// 121 | #endif // not APSTUDIO_INVOKED 122 | -------------------------------------------------------------------------------- /example/windows/runner/flutter_window.cpp: -------------------------------------------------------------------------------- 1 | #include "flutter_window.h" 2 | 3 | #include 4 | 5 | #include "flutter/generated_plugin_registrant.h" 6 | 7 | FlutterWindow::FlutterWindow(const flutter::DartProject& project) 8 | : project_(project) {} 9 | 10 | FlutterWindow::~FlutterWindow() {} 11 | 12 | bool FlutterWindow::OnCreate() { 13 | if (!Win32Window::OnCreate()) { 14 | return false; 15 | } 16 | 17 | RECT frame = GetClientArea(); 18 | 19 | // The size here must match the window dimensions to avoid unnecessary surface 20 | // creation / destruction in the startup path. 21 | flutter_controller_ = std::make_unique( 22 | frame.right - frame.left, frame.bottom - frame.top, project_); 23 | // Ensure that basic setup of the controller was successful. 24 | if (!flutter_controller_->engine() || !flutter_controller_->view()) { 25 | return false; 26 | } 27 | RegisterPlugins(flutter_controller_->engine()); 28 | SetChildContent(flutter_controller_->view()->GetNativeWindow()); 29 | return true; 30 | } 31 | 32 | void FlutterWindow::OnDestroy() { 33 | if (flutter_controller_) { 34 | flutter_controller_ = nullptr; 35 | } 36 | 37 | Win32Window::OnDestroy(); 38 | } 39 | 40 | LRESULT 41 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message, 42 | WPARAM const wparam, 43 | LPARAM const lparam) noexcept { 44 | // Give Flutter, including plugins, an opportunity to handle window messages. 45 | if (flutter_controller_) { 46 | std::optional result = 47 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, 48 | lparam); 49 | if (result) { 50 | return *result; 51 | } 52 | } 53 | 54 | switch (message) { 55 | case WM_FONTCHANGE: 56 | flutter_controller_->engine()->ReloadSystemFonts(); 57 | break; 58 | } 59 | 60 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam); 61 | } 62 | -------------------------------------------------------------------------------- /example/windows/runner/flutter_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_FLUTTER_WINDOW_H_ 2 | #define RUNNER_FLUTTER_WINDOW_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "win32_window.h" 10 | 11 | // A window that does nothing but host a Flutter view. 12 | class FlutterWindow : public Win32Window { 13 | public: 14 | // Creates a new FlutterWindow hosting a Flutter view running |project|. 15 | explicit FlutterWindow(const flutter::DartProject& project); 16 | virtual ~FlutterWindow(); 17 | 18 | protected: 19 | // Win32Window: 20 | bool OnCreate() override; 21 | void OnDestroy() override; 22 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, 23 | LPARAM const lparam) noexcept override; 24 | 25 | private: 26 | // The project to run. 27 | flutter::DartProject project_; 28 | 29 | // The Flutter instance hosted by this window. 30 | std::unique_ptr flutter_controller_; 31 | }; 32 | 33 | #endif // RUNNER_FLUTTER_WINDOW_H_ 34 | -------------------------------------------------------------------------------- /example/windows/runner/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "flutter_window.h" 6 | #include "utils.h" 7 | 8 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, 9 | _In_ wchar_t *command_line, _In_ int show_command) { 10 | // Attach to console when present (e.g., 'flutter run') or create a 11 | // new console when running with a debugger. 12 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { 13 | CreateAndAttachConsole(); 14 | } 15 | 16 | // Initialize COM, so that it is available for use in the library and/or 17 | // plugins. 18 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); 19 | 20 | flutter::DartProject project(L"data"); 21 | 22 | std::vector command_line_arguments = 23 | GetCommandLineArguments(); 24 | 25 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); 26 | 27 | FlutterWindow window(project); 28 | Win32Window::Point origin(10, 10); 29 | Win32Window::Size size(1280, 720); 30 | if (!window.CreateAndShow(L"example", origin, size)) { 31 | return EXIT_FAILURE; 32 | } 33 | window.SetQuitOnClose(true); 34 | 35 | ::MSG msg; 36 | while (::GetMessage(&msg, nullptr, 0, 0)) { 37 | ::TranslateMessage(&msg); 38 | ::DispatchMessage(&msg); 39 | } 40 | 41 | ::CoUninitialize(); 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /example/windows/runner/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by Runner.rc 4 | // 5 | #define IDI_APP_ICON 101 6 | 7 | // Next default values for new objects 8 | // 9 | #ifdef APSTUDIO_INVOKED 10 | #ifndef APSTUDIO_READONLY_SYMBOLS 11 | #define _APS_NEXT_RESOURCE_VALUE 102 12 | #define _APS_NEXT_COMMAND_VALUE 40001 13 | #define _APS_NEXT_CONTROL_VALUE 1001 14 | #define _APS_NEXT_SYMED_VALUE 101 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /example/windows/runner/resources/app_icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnpryan/go_router_prototype/d131f6609b9e20c34fd9af5dcc2a2743ba436cfe/example/windows/runner/resources/app_icon.ico -------------------------------------------------------------------------------- /example/windows/runner/runner.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PerMonitorV2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /example/windows/runner/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | void CreateAndAttachConsole() { 11 | if (::AllocConsole()) { 12 | FILE *unused; 13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) { 14 | _dup2(_fileno(stdout), 1); 15 | } 16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) { 17 | _dup2(_fileno(stdout), 2); 18 | } 19 | std::ios::sync_with_stdio(); 20 | FlutterDesktopResyncOutputStreams(); 21 | } 22 | } 23 | 24 | std::vector GetCommandLineArguments() { 25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. 26 | int argc; 27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); 28 | if (argv == nullptr) { 29 | return std::vector(); 30 | } 31 | 32 | std::vector command_line_arguments; 33 | 34 | // Skip the first argument as it's the binary name. 35 | for (int i = 1; i < argc; i++) { 36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i])); 37 | } 38 | 39 | ::LocalFree(argv); 40 | 41 | return command_line_arguments; 42 | } 43 | 44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) { 45 | if (utf16_string == nullptr) { 46 | return std::string(); 47 | } 48 | int target_length = ::WideCharToMultiByte( 49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 50 | -1, nullptr, 0, nullptr, nullptr); 51 | if (target_length == 0) { 52 | return std::string(); 53 | } 54 | std::string utf8_string; 55 | utf8_string.resize(target_length); 56 | int converted_length = ::WideCharToMultiByte( 57 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 58 | -1, utf8_string.data(), 59 | target_length, nullptr, nullptr); 60 | if (converted_length == 0) { 61 | return std::string(); 62 | } 63 | return utf8_string; 64 | } 65 | -------------------------------------------------------------------------------- /example/windows/runner/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_UTILS_H_ 2 | #define RUNNER_UTILS_H_ 3 | 4 | #include 5 | #include 6 | 7 | // Creates a console for the process, and redirects stdout and stderr to 8 | // it for both the runner and the Flutter library. 9 | void CreateAndAttachConsole(); 10 | 11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string 12 | // encoded in UTF-8. Returns an empty std::string on failure. 13 | std::string Utf8FromUtf16(const wchar_t* utf16_string); 14 | 15 | // Gets the command line arguments passed in as a std::vector, 16 | // encoded in UTF-8. Returns an empty std::vector on failure. 17 | std::vector GetCommandLineArguments(); 18 | 19 | #endif // RUNNER_UTILS_H_ 20 | -------------------------------------------------------------------------------- /example/windows/runner/win32_window.cpp: -------------------------------------------------------------------------------- 1 | #include "win32_window.h" 2 | 3 | #include 4 | 5 | #include "resource.h" 6 | 7 | namespace { 8 | 9 | constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; 10 | 11 | // The number of Win32Window objects that currently exist. 12 | static int g_active_window_count = 0; 13 | 14 | using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); 15 | 16 | // Scale helper to convert logical scaler values to physical using passed in 17 | // scale factor 18 | int Scale(int source, double scale_factor) { 19 | return static_cast(source * scale_factor); 20 | } 21 | 22 | // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. 23 | // This API is only needed for PerMonitor V1 awareness mode. 24 | void EnableFullDpiSupportIfAvailable(HWND hwnd) { 25 | HMODULE user32_module = LoadLibraryA("User32.dll"); 26 | if (!user32_module) { 27 | return; 28 | } 29 | auto enable_non_client_dpi_scaling = 30 | reinterpret_cast( 31 | GetProcAddress(user32_module, "EnableNonClientDpiScaling")); 32 | if (enable_non_client_dpi_scaling != nullptr) { 33 | enable_non_client_dpi_scaling(hwnd); 34 | FreeLibrary(user32_module); 35 | } 36 | } 37 | 38 | } // namespace 39 | 40 | // Manages the Win32Window's window class registration. 41 | class WindowClassRegistrar { 42 | public: 43 | ~WindowClassRegistrar() = default; 44 | 45 | // Returns the singleton registar instance. 46 | static WindowClassRegistrar* GetInstance() { 47 | if (!instance_) { 48 | instance_ = new WindowClassRegistrar(); 49 | } 50 | return instance_; 51 | } 52 | 53 | // Returns the name of the window class, registering the class if it hasn't 54 | // previously been registered. 55 | const wchar_t* GetWindowClass(); 56 | 57 | // Unregisters the window class. Should only be called if there are no 58 | // instances of the window. 59 | void UnregisterWindowClass(); 60 | 61 | private: 62 | WindowClassRegistrar() = default; 63 | 64 | static WindowClassRegistrar* instance_; 65 | 66 | bool class_registered_ = false; 67 | }; 68 | 69 | WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; 70 | 71 | const wchar_t* WindowClassRegistrar::GetWindowClass() { 72 | if (!class_registered_) { 73 | WNDCLASS window_class{}; 74 | window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); 75 | window_class.lpszClassName = kWindowClassName; 76 | window_class.style = CS_HREDRAW | CS_VREDRAW; 77 | window_class.cbClsExtra = 0; 78 | window_class.cbWndExtra = 0; 79 | window_class.hInstance = GetModuleHandle(nullptr); 80 | window_class.hIcon = 81 | LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); 82 | window_class.hbrBackground = 0; 83 | window_class.lpszMenuName = nullptr; 84 | window_class.lpfnWndProc = Win32Window::WndProc; 85 | RegisterClass(&window_class); 86 | class_registered_ = true; 87 | } 88 | return kWindowClassName; 89 | } 90 | 91 | void WindowClassRegistrar::UnregisterWindowClass() { 92 | UnregisterClass(kWindowClassName, nullptr); 93 | class_registered_ = false; 94 | } 95 | 96 | Win32Window::Win32Window() { 97 | ++g_active_window_count; 98 | } 99 | 100 | Win32Window::~Win32Window() { 101 | --g_active_window_count; 102 | Destroy(); 103 | } 104 | 105 | bool Win32Window::CreateAndShow(const std::wstring& title, 106 | const Point& origin, 107 | const Size& size) { 108 | Destroy(); 109 | 110 | const wchar_t* window_class = 111 | WindowClassRegistrar::GetInstance()->GetWindowClass(); 112 | 113 | const POINT target_point = {static_cast(origin.x), 114 | static_cast(origin.y)}; 115 | HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); 116 | UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); 117 | double scale_factor = dpi / 96.0; 118 | 119 | HWND window = CreateWindow( 120 | window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, 121 | Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), 122 | Scale(size.width, scale_factor), Scale(size.height, scale_factor), 123 | nullptr, nullptr, GetModuleHandle(nullptr), this); 124 | 125 | if (!window) { 126 | return false; 127 | } 128 | 129 | return OnCreate(); 130 | } 131 | 132 | // static 133 | LRESULT CALLBACK Win32Window::WndProc(HWND const window, 134 | UINT const message, 135 | WPARAM const wparam, 136 | LPARAM const lparam) noexcept { 137 | if (message == WM_NCCREATE) { 138 | auto window_struct = reinterpret_cast(lparam); 139 | SetWindowLongPtr(window, GWLP_USERDATA, 140 | reinterpret_cast(window_struct->lpCreateParams)); 141 | 142 | auto that = static_cast(window_struct->lpCreateParams); 143 | EnableFullDpiSupportIfAvailable(window); 144 | that->window_handle_ = window; 145 | } else if (Win32Window* that = GetThisFromHandle(window)) { 146 | return that->MessageHandler(window, message, wparam, lparam); 147 | } 148 | 149 | return DefWindowProc(window, message, wparam, lparam); 150 | } 151 | 152 | LRESULT 153 | Win32Window::MessageHandler(HWND hwnd, 154 | UINT const message, 155 | WPARAM const wparam, 156 | LPARAM const lparam) noexcept { 157 | switch (message) { 158 | case WM_DESTROY: 159 | window_handle_ = nullptr; 160 | Destroy(); 161 | if (quit_on_close_) { 162 | PostQuitMessage(0); 163 | } 164 | return 0; 165 | 166 | case WM_DPICHANGED: { 167 | auto newRectSize = reinterpret_cast(lparam); 168 | LONG newWidth = newRectSize->right - newRectSize->left; 169 | LONG newHeight = newRectSize->bottom - newRectSize->top; 170 | 171 | SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, 172 | newHeight, SWP_NOZORDER | SWP_NOACTIVATE); 173 | 174 | return 0; 175 | } 176 | case WM_SIZE: { 177 | RECT rect = GetClientArea(); 178 | if (child_content_ != nullptr) { 179 | // Size and position the child window. 180 | MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, 181 | rect.bottom - rect.top, TRUE); 182 | } 183 | return 0; 184 | } 185 | 186 | case WM_ACTIVATE: 187 | if (child_content_ != nullptr) { 188 | SetFocus(child_content_); 189 | } 190 | return 0; 191 | } 192 | 193 | return DefWindowProc(window_handle_, message, wparam, lparam); 194 | } 195 | 196 | void Win32Window::Destroy() { 197 | OnDestroy(); 198 | 199 | if (window_handle_) { 200 | DestroyWindow(window_handle_); 201 | window_handle_ = nullptr; 202 | } 203 | if (g_active_window_count == 0) { 204 | WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); 205 | } 206 | } 207 | 208 | Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { 209 | return reinterpret_cast( 210 | GetWindowLongPtr(window, GWLP_USERDATA)); 211 | } 212 | 213 | void Win32Window::SetChildContent(HWND content) { 214 | child_content_ = content; 215 | SetParent(content, window_handle_); 216 | RECT frame = GetClientArea(); 217 | 218 | MoveWindow(content, frame.left, frame.top, frame.right - frame.left, 219 | frame.bottom - frame.top, true); 220 | 221 | SetFocus(child_content_); 222 | } 223 | 224 | RECT Win32Window::GetClientArea() { 225 | RECT frame; 226 | GetClientRect(window_handle_, &frame); 227 | return frame; 228 | } 229 | 230 | HWND Win32Window::GetHandle() { 231 | return window_handle_; 232 | } 233 | 234 | void Win32Window::SetQuitOnClose(bool quit_on_close) { 235 | quit_on_close_ = quit_on_close; 236 | } 237 | 238 | bool Win32Window::OnCreate() { 239 | // No-op; provided for subclasses. 240 | return true; 241 | } 242 | 243 | void Win32Window::OnDestroy() { 244 | // No-op; provided for subclasses. 245 | } 246 | -------------------------------------------------------------------------------- /example/windows/runner/win32_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_WIN32_WINDOW_H_ 2 | #define RUNNER_WIN32_WINDOW_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be 11 | // inherited from by classes that wish to specialize with custom 12 | // rendering and input handling 13 | class Win32Window { 14 | public: 15 | struct Point { 16 | unsigned int x; 17 | unsigned int y; 18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {} 19 | }; 20 | 21 | struct Size { 22 | unsigned int width; 23 | unsigned int height; 24 | Size(unsigned int width, unsigned int height) 25 | : width(width), height(height) {} 26 | }; 27 | 28 | Win32Window(); 29 | virtual ~Win32Window(); 30 | 31 | // Creates and shows a win32 window with |title| and position and size using 32 | // |origin| and |size|. New windows are created on the default monitor. Window 33 | // sizes are specified to the OS in physical pixels, hence to ensure a 34 | // consistent size to will treat the width height passed in to this function 35 | // as logical pixels and scale to appropriate for the default monitor. Returns 36 | // true if the window was created successfully. 37 | bool CreateAndShow(const std::wstring& title, 38 | const Point& origin, 39 | const Size& size); 40 | 41 | // Release OS resources associated with window. 42 | void Destroy(); 43 | 44 | // Inserts |content| into the window tree. 45 | void SetChildContent(HWND content); 46 | 47 | // Returns the backing Window handle to enable clients to set icon and other 48 | // window properties. Returns nullptr if the window has been destroyed. 49 | HWND GetHandle(); 50 | 51 | // If true, closing this window will quit the application. 52 | void SetQuitOnClose(bool quit_on_close); 53 | 54 | // Return a RECT representing the bounds of the current client area. 55 | RECT GetClientArea(); 56 | 57 | protected: 58 | // Processes and route salient window messages for mouse handling, 59 | // size change and DPI. Delegates handling of these to member overloads that 60 | // inheriting classes can handle. 61 | virtual LRESULT MessageHandler(HWND window, 62 | UINT const message, 63 | WPARAM const wparam, 64 | LPARAM const lparam) noexcept; 65 | 66 | // Called when CreateAndShow is called, allowing subclass window-related 67 | // setup. Subclasses should return false if setup fails. 68 | virtual bool OnCreate(); 69 | 70 | // Called when Destroy is called. 71 | virtual void OnDestroy(); 72 | 73 | private: 74 | friend class WindowClassRegistrar; 75 | 76 | // OS callback called by message pump. Handles the WM_NCCREATE message which 77 | // is passed when the non-client area is being created and enables automatic 78 | // non-client DPI scaling so that the non-client area automatically 79 | // responsponds to changes in DPI. All other messages are handled by 80 | // MessageHandler. 81 | static LRESULT CALLBACK WndProc(HWND const window, 82 | UINT const message, 83 | WPARAM const wparam, 84 | LPARAM const lparam) noexcept; 85 | 86 | // Retrieves a class instance pointer for |window| 87 | static Win32Window* GetThisFromHandle(HWND const window) noexcept; 88 | 89 | bool quit_on_close_ = false; 90 | 91 | // window handle for top level window. 92 | HWND window_handle_ = nullptr; 93 | 94 | // window handle for hosted content. 95 | HWND child_content_ = nullptr; 96 | }; 97 | 98 | #endif // RUNNER_WIN32_WINDOW_H_ 99 | -------------------------------------------------------------------------------- /lib/go_router_prototype.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | library tree_router; 6 | 7 | import 'package:flutter/foundation.dart'; 8 | 9 | import 'src/delegate.dart'; 10 | import 'src/parser.dart'; 11 | import 'src/route.dart'; 12 | 13 | export 'src/route.dart'; 14 | export 'src/state.dart'; 15 | export 'src/typedefs.dart'; 16 | 17 | class GoRouter { 18 | final GoRouterDelegate delegate; 19 | final GoRouteInformationParser parser; 20 | 21 | GoRouter({ 22 | required List routes, 23 | Listenable? refreshListenable, 24 | }) : delegate = 25 | GoRouterDelegate(routes, refreshListenable: refreshListenable), 26 | parser = GoRouteInformationParser(); 27 | } 28 | -------------------------------------------------------------------------------- /lib/src/builder.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/src/inheritance.dart'; 7 | import 'package:go_router_prototype/src/match.dart'; 8 | import 'package:go_router_prototype/src/typedefs.dart'; 9 | 10 | import 'route.dart' as r; 11 | import 'state.dart'; 12 | 13 | Widget buildMatch(BuildContext context, RouteMatch routeMatch, VoidCallback pop, 14 | Key navigatorKey) { 15 | return _buildMatchRecursive(context, routeMatch, 0, pop, navigatorKey).widget; 16 | } 17 | 18 | // Builds a Navigator for all matched Routes from [startIndex] until the end of 19 | // the the list, or if a route is a NavigatorRoute 20 | _RecursiveBuildResult _buildMatchRecursive(BuildContext context, 21 | RouteMatch routeMatch, int startIndex, VoidCallback pop, Key navigatorKey, 22 | {Page? firstPage}) { 23 | final pages = []; 24 | if (firstPage != null) pages.add(firstPage); 25 | for (var i = startIndex; i < routeMatch.routes.length; i++) { 26 | final route = routeMatch.routes[i]; 27 | if (route is r.StackedRoute) { 28 | final page = _buildPage(context, route, routeMatch); 29 | pages.add(page); 30 | } else if (route is r.ShellRoute) { 31 | final result = _buildShellRecursive(context, routeMatch, i, pop); 32 | final child = result.widget; 33 | pages.add(_pageForPlatform(child: child)); 34 | i = result.newIndex; 35 | } else if (route is r.NestedStackRoute) { 36 | // Build the first page to display 37 | final page = _buildPage(context, route, routeMatch); 38 | // Build the inner Navigator it by recursively calling this method and 39 | // returning the result directly. 40 | final key = ValueKey(route); 41 | final innerNav = _buildMatchRecursive( 42 | context, routeMatch, i + 1, pop, key, 43 | firstPage: page); 44 | return innerNav; 45 | } 46 | } 47 | 48 | if (pages.isEmpty) { 49 | throw Exception( 50 | 'Attempt to build a Navigator was built with an empty pages list'); 51 | } 52 | 53 | Widget navigator = Navigator( 54 | key: navigatorKey, 55 | pages: pages, 56 | onPopPage: (Route route, dynamic result) { 57 | if (!route.didPop(result)) { 58 | return false; 59 | } 60 | // TODO: Pop from the correct Navigator with route.navigator 61 | pop(); 62 | return true; 63 | }, 64 | ); 65 | 66 | return _RecursiveBuildResult(navigator, routeMatch.routes.length); 67 | } 68 | 69 | class _RecursiveBuildResult { 70 | final Widget widget; 71 | final int newIndex; 72 | 73 | _RecursiveBuildResult(this.widget, this.newIndex); 74 | } 75 | 76 | _RecursiveBuildResult _buildShellRecursive( 77 | BuildContext context, RouteMatch routeMatch, int i, VoidCallback pop) { 78 | final parent = routeMatch.routes[i] as r.ShellRoute; 79 | late final r.RouteBase? child; 80 | 81 | if (i + 1 < routeMatch.routes.length) { 82 | child = routeMatch.routes[i + 1]; 83 | } else { 84 | child = null; 85 | } 86 | 87 | Widget? childWidget; 88 | if (child is r.StackedRoute) { 89 | childWidget = _callRouteBuilder(context, child); 90 | i++; 91 | } else if (child is r.ShellRoute) { 92 | final result = _buildShellRecursive(context, routeMatch, i + 1, pop); 93 | childWidget = result.widget; 94 | i = result.newIndex; 95 | } else if (child is r.NestedStackRoute) { 96 | final key = ValueKey(child); 97 | final result = _buildMatchRecursive(context, routeMatch, i + 1, pop, key); 98 | childWidget = result.widget; 99 | i = result.newIndex; 100 | } else if (child == null) { 101 | childWidget = const SizedBox.shrink(); 102 | i++; 103 | } 104 | 105 | final parentWidget = _callRouteBuilder(context, parent, child: childWidget!); 106 | 107 | return _RecursiveBuildResult(parentWidget, i); 108 | } 109 | 110 | Page _pageForPlatform({required Widget child}) { 111 | return MaterialPage(child: child); 112 | } 113 | 114 | Widget _callRouteBuilder(BuildContext context, r.RouteBase route, 115 | {Widget? child}) { 116 | late final StackedRouteBuilder builder; 117 | if (route is r.NestedStackRoute) { 118 | builder = route.builder; 119 | } else if (route is r.StackedRoute) { 120 | builder = route.builder; 121 | } else if (route is r.ShellRoute) { 122 | if (child == null) { 123 | throw ('Attempt to build ShellRoute without a child widget'); 124 | } 125 | return _wrapWithRouteStateScope(context, route, 126 | Builder(builder: (context) => route.builder(context, child))); 127 | } 128 | 129 | // The context passed to the builder must be below RouteStateScope. 130 | return _wrapWithRouteStateScope( 131 | context, route, Builder(builder: (context) => builder(context))); 132 | } 133 | 134 | Page _buildPage( 135 | BuildContext context, r.RouteBase route, RouteMatch routeMatch) { 136 | return _pageForPlatform(child: _callRouteBuilder(context, route)); 137 | } 138 | 139 | Widget _wrapWithRouteStateScope( 140 | BuildContext context, r.RouteBase route, Widget child) { 141 | final globalState = GlobalRouteState.of(context); 142 | if (globalState == null) { 143 | throw Exception('No GlobalRouteState found during route build phase'); 144 | } 145 | return RouteStateScope( 146 | state: RouteState(route, globalState), 147 | child: child, 148 | ); 149 | } 150 | -------------------------------------------------------------------------------- /lib/src/delegate.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/foundation.dart'; 6 | import 'package:flutter/widgets.dart'; 7 | import 'package:go_router_prototype/src/builder.dart'; 8 | 9 | import 'inheritance.dart'; 10 | import 'route.dart'; 11 | import 'state.dart'; 12 | 13 | class GoRouterDelegate extends RouterDelegate 14 | with ChangeNotifier, PopNavigatorRouterDelegateMixin { 15 | late final GlobalRouteState _globalRouteState; 16 | final Listenable? refreshListenable; 17 | 18 | factory GoRouterDelegate( 19 | List routes, { 20 | Listenable? refreshListenable, 21 | }) { 22 | final state = GlobalRouteState(routes); 23 | return GoRouterDelegate.withState( 24 | state, 25 | refreshListenable: refreshListenable, 26 | ); 27 | } 28 | 29 | GoRouterDelegate.withState( 30 | this._globalRouteState, { 31 | this.refreshListenable, 32 | }) { 33 | _globalRouteState.addListener(notifyListeners); 34 | refreshListenable?.addListener(() { 35 | setNewRoutePath(currentConfiguration); 36 | }); 37 | } 38 | 39 | @override 40 | void dispose() { 41 | _globalRouteState.removeListener(notifyListeners); 42 | super.dispose(); 43 | } 44 | 45 | @override 46 | Widget build(BuildContext context) { 47 | return GlobalRouteStateScope( 48 | state: _globalRouteState, 49 | child: Builder(builder: (context) { 50 | return buildMatch( 51 | context, 52 | _globalRouteState.match, 53 | () => _globalRouteState.pop(), 54 | navigatorKey, 55 | ); 56 | }), 57 | ); 58 | } 59 | 60 | @override 61 | Uri get currentConfiguration { 62 | final match = _globalRouteState.match; 63 | final current = match.path; 64 | final currentUri = Uri.parse(current); 65 | return currentUri; 66 | } 67 | 68 | @override 69 | final GlobalKey navigatorKey = GlobalKey(); 70 | 71 | @override 72 | Future setNewRoutePath(Uri configuration) async { 73 | // TODO: This is probably using decodeComponent incorrectly. 74 | await _globalRouteState.goTo(Uri.decodeComponent(configuration.toString())); 75 | return SynchronousFuture(null); 76 | } 77 | 78 | @override 79 | Future setInitialRoutePath(Uri configuration) async { 80 | await _globalRouteState.goTo(Uri.decodeComponent(configuration.toString()), 81 | isInitial: true); 82 | return SynchronousFuture(null); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /lib/src/inheritance.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/cupertino.dart'; 6 | 7 | import 'state.dart'; 8 | 9 | class RouteStateScope extends InheritedWidget { 10 | final RouteState state; 11 | 12 | RouteStateScope({required this.state, required Widget child}) 13 | : super(child: child, key: ValueKey(state.route)); 14 | 15 | @override 16 | bool updateShouldNotify(covariant InheritedWidget oldWidget) { 17 | return oldWidget is RouteStateScope && state != oldWidget.state; 18 | } 19 | } 20 | 21 | class GlobalRouteStateScope extends InheritedWidget { 22 | final GlobalRouteState state; 23 | 24 | const GlobalRouteStateScope({ 25 | required this.state, 26 | required Widget child, 27 | Key? key, 28 | }) : super(child: child, key: key); 29 | 30 | @override 31 | bool updateShouldNotify(covariant InheritedWidget oldWidget) { 32 | return oldWidget is GlobalRouteStateScope && state != oldWidget.state; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /lib/src/match.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:collection/collection.dart'; 6 | import 'package:path/path.dart' as p; 7 | import 'package:quiver/core.dart'; 8 | import 'package:go_router_prototype/src/matching.dart'; 9 | 10 | import 'parameters.dart'; 11 | import 'route.dart'; 12 | 13 | class RouteMatch { 14 | static const _listEquality = ListEquality(); 15 | 16 | final List routes; 17 | final Parameters parameters; 18 | 19 | const RouteMatch({ 20 | required this.routes, 21 | required this.parameters, 22 | }); 23 | 24 | RouteBase? getLast() => routes.isEmpty ? null : routes.last; 25 | 26 | String get path { 27 | return fillParameters(p.joinAll(routes.map((r) => r.path)), parameters); 28 | } 29 | 30 | bool isPrefixOf(RouteMatch other) { 31 | if (other.routes.length < routes.length) { 32 | return false; 33 | } 34 | for (var i = 0; i < routes.length; i++) { 35 | if (routes[i].path != other.routes[i].path) { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | 42 | // Returns the index of [other.routes] where this route's paths no longer 43 | // match. 44 | int getMatchingPrefixIndex(RouteMatch other) { 45 | for (var i = 0; i < other.routes.length; i++) { 46 | if (i >= routes.length) { 47 | return i; 48 | } 49 | if (routes[i].path != other.routes[i].path) { 50 | return i; 51 | } 52 | } 53 | // If they are the same length, and no mismatch was found, return the 54 | // length so that redirect loops can be avoided. 55 | if (routes.length == other.routes.length) { 56 | return routes.length; 57 | } 58 | return -1; 59 | } 60 | 61 | @override 62 | bool operator ==(Object other) { 63 | return other is RouteMatch && 64 | _listEquality.equals(other.routes, routes) && 65 | other.parameters == parameters; 66 | } 67 | 68 | @override 69 | int get hashCode => hash2(path, _listEquality.hash(routes)); 70 | 71 | @override 72 | String toString() { 73 | return 'RouteMatch: $routes, $parameters'; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /lib/src/matching.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:path_to_regexp/path_to_regexp.dart'; 6 | 7 | import 'parameters.dart'; 8 | 9 | bool hasMatch(String template, String path) { 10 | return _hasMatch(template, path, true); 11 | } 12 | 13 | bool hasExactMatch(String template, String path) { 14 | return _hasMatch(template, path, false); 15 | } 16 | 17 | bool _hasMatch(String template, String path, bool prefix) { 18 | final parameters = []; 19 | 20 | // remove query parameters 21 | path = Uri.decodeComponent(Uri.parse(path).path); 22 | 23 | var pathRegExp = pathToRegExp(template, 24 | parameters: parameters, prefix: prefix, caseSensitive: true); 25 | return pathRegExp.hasMatch(path); 26 | } 27 | 28 | Parameters extractParameters(String template, String path) { 29 | final queryParams = Uri.parse(path).queryParameters; 30 | final parameters = []; 31 | var pathRegExp = pathToRegExp(template, 32 | parameters: parameters, prefix: true, caseSensitive: true); 33 | final match = pathRegExp.matchAsPrefix(path); 34 | if (match == null) return Parameters({}, queryParams); 35 | return Parameters(extract(parameters, match), queryParams); 36 | } 37 | 38 | final _fillRegex = RegExp(r'\:([A-Za-z0-9- .%]*)'); 39 | 40 | String fillParameters(String template, Parameters parameters) { 41 | final filledPaths = template.replaceAllMapped(_fillRegex, (match) { 42 | var paramName = match.group(0)!.replaceAll(':', ''); 43 | if (parameters.path.containsKey(paramName)) { 44 | return parameters.path[paramName]!; 45 | } 46 | return ''; 47 | }); 48 | 49 | // Uri.toString() adds a '?' if there are no query parameters so skip if there 50 | // aren't any. 51 | if (parameters.query.isEmpty) { 52 | return filledPaths; 53 | } 54 | return Uri.parse(filledPaths) 55 | .replace(queryParameters: parameters.query) 56 | .toString(); 57 | } 58 | 59 | List parseParameterNames(String path) { 60 | final List result = []; 61 | final matches = _fillRegex.allMatches(path); 62 | 63 | for (var match in matches) { 64 | assert(match.groupCount <= 1); 65 | 66 | if (match.groupCount == 1) { 67 | final matchedStr = match.group(0); 68 | if (matchedStr != null) { 69 | result.add(matchedStr.replaceAll(':', '')); 70 | } 71 | } 72 | } 73 | return result; 74 | } 75 | -------------------------------------------------------------------------------- /lib/src/parameters.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:collection/collection.dart'; 6 | import 'package:quiver/core.dart'; 7 | 8 | class Parameters { 9 | final Map path; 10 | final Map query; 11 | 12 | Parameters(this.path, this.query); 13 | Parameters.empty() 14 | : path = {}, 15 | query = {}; 16 | 17 | static const _equality = MapEquality(); 18 | 19 | @override 20 | bool operator ==(Object other) { 21 | return other is Parameters && 22 | _equality.equals(path, other.path) && 23 | _equality.equals(query, other.query); 24 | } 25 | 26 | @override 27 | int get hashCode => hash2(_equality.hash(path), _equality.hash(query)); 28 | 29 | @override 30 | String toString() => 'Parameters: $path $query'; 31 | } 32 | -------------------------------------------------------------------------------- /lib/src/parser.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/foundation.dart'; 6 | import 'package:flutter/widgets.dart'; 7 | 8 | class GoRouteInformationParser extends RouteInformationParser { 9 | @override 10 | Future parseRouteInformation( 11 | RouteInformation routeInformation, 12 | ) => 13 | SynchronousFuture(Uri.parse(routeInformation.location!)); 14 | 15 | @override 16 | RouteInformation restoreRouteInformation(Uri configuration) => 17 | RouteInformation(location: configuration.toString()); 18 | } 19 | -------------------------------------------------------------------------------- /lib/src/route.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:collection/collection.dart'; 6 | import 'package:quiver/core.dart'; 7 | 8 | import 'typedefs.dart'; 9 | 10 | /// A route that is displayed visually above the matching parent route using the 11 | /// [Navigator]. 12 | /// 13 | /// The widget returned by [builder] is wrapped in [Page]and provided to the 14 | /// root Navigator or the Navigator belonging to the nearest [NestedStackRoute] 15 | /// ancestor. The page will be either a [MaterialPage] or [CupertinoPage] depending 16 | /// on the application type. 17 | /// 18 | /// This route has the same behavior as GoRoute in go_router >=3.0.0. 19 | class StackedRoute extends RouteBase { 20 | final StackedRouteBuilder builder; 21 | 22 | StackedRoute({ 23 | required String path, 24 | required this.builder, 25 | Redirect? redirect, 26 | List routes = const [], 27 | }) : super( 28 | path: path, 29 | routes: routes, 30 | redirect: redirect, 31 | ); 32 | } 33 | 34 | /// A route that displays a UI shell around the matching child route. 35 | /// 36 | /// The widget built by the matching child route becomes to the child parameter 37 | /// of the [builder]. 38 | class ShellRoute extends RouteBase { 39 | final ShellRouteBuilder builder; 40 | final String? defaultRoute; 41 | 42 | ShellRoute({ 43 | required String path, 44 | required this.builder, 45 | this.defaultRoute, 46 | Redirect? redirect, 47 | List routes = const [], 48 | }) : super( 49 | path: path, 50 | routes: routes, 51 | redirect: redirect, 52 | ); 53 | } 54 | 55 | /// A route that displays descendent [StackedRoute]s within its visual boundary. 56 | /// 57 | /// This route places a nested [Navigator] in the widget tree, where any 58 | /// descendent [StackedRoute]s are placed onto this 59 | /// Navigator instead of the root Navigator, which allows you to display a UI 60 | /// shell around a nested stack of routes if this route is a child route of 61 | /// [ShellRoute]. 62 | class NestedStackRoute extends RouteBase { 63 | final NavigatorRouteBuilder builder; 64 | 65 | NestedStackRoute({ 66 | required String path, 67 | required this.builder, 68 | Redirect? redirect, 69 | List routes = const [], 70 | }) : super( 71 | path: path, 72 | routes: routes, 73 | redirect: redirect, 74 | ); 75 | } 76 | 77 | abstract class RouteBase { 78 | static const _listEquality = ListEquality(); 79 | 80 | final String path; 81 | final List routes; 82 | final Redirect? redirect; 83 | 84 | const RouteBase({ 85 | required this.path, 86 | this.routes = const [], 87 | this.redirect, 88 | }); 89 | 90 | @override 91 | bool operator ==(Object other) => 92 | other is RouteBase && 93 | other.path == path && 94 | _listEquality.equals(other.routes, routes); 95 | 96 | @override 97 | int get hashCode => hash2(path, _listEquality.hash(routes)); 98 | 99 | @override 100 | String toString() => 'Route: $path'; 101 | } 102 | -------------------------------------------------------------------------------- /lib/src/state.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/foundation.dart'; 6 | import 'package:flutter/widgets.dart'; 7 | import 'package:go_router_prototype/src/inheritance.dart'; 8 | 9 | import 'match.dart'; 10 | import 'route.dart'; 11 | import 'tree.dart'; 12 | 13 | class GlobalRouteState extends ChangeNotifier { 14 | final RouteTree _routeTree; 15 | late RouteMatch _match; 16 | 17 | GlobalRouteState(List routes) : _routeTree = RouteTree(routes) { 18 | _match = _routeTree.get('/'); 19 | } 20 | 21 | Future setMatch(RouteMatch match) async { 22 | match = await _handleRedirects(match); 23 | _match = match; 24 | notifyListeners(); 25 | } 26 | 27 | RouteMatch get match => _match; 28 | 29 | void pop() { 30 | _match = _routeTree.pop(_match); 31 | notifyListeners(); 32 | } 33 | 34 | Future goTo(String path, 35 | {RouteBase? parentRoute, bool isInitial = false}) async { 36 | if (isInitial) { 37 | await setMatch(_routeTree.get(path)); 38 | } else { 39 | await setMatch(_routeTree.get(path, 40 | parentRoute: parentRoute, previousMatch: _match)); 41 | } 42 | } 43 | 44 | Future _handleRedirects(RouteMatch match) async { 45 | return _handleRedirectsRecursive(match); 46 | } 47 | 48 | Future _handleRedirectsRecursive(RouteMatch match, 49 | {int endIndex = 0}) async { 50 | if (endIndex < 0) endIndex = 0; 51 | for (var i = match.routes.length - 1; i >= endIndex; i--) { 52 | final route = match.routes[i]; 53 | final redirect = route.redirect; 54 | if (redirect != null) { 55 | final newPath = await redirect(match); 56 | if (newPath != null) { 57 | final newMatch = _routeTree.get( 58 | newPath, 59 | parentRoute: route, 60 | previousMatch: match, 61 | ); 62 | // If the previous match is a prefix of the new match, stop searching 63 | // for redirects at the point where the two routes are the same. 64 | // 65 | // For example, if the previous match was '/a/b', and the new match is 66 | // /a/b/c, we can skip searching '/a/b' for redirects, since those 67 | // will be handled by previous invocations of this method on the call 68 | // stack. 69 | if (match.isPrefixOf(newMatch)) { 70 | final endIndex = match.getMatchingPrefixIndex(newMatch); 71 | return _handleRedirectsRecursive(newMatch, endIndex: endIndex); 72 | } 73 | return _handleRedirectsRecursive(newMatch); 74 | } 75 | } 76 | } 77 | return SynchronousFuture(match); 78 | } 79 | 80 | static GlobalRouteState? of(BuildContext context) { 81 | final scope = 82 | context.dependOnInheritedWidgetOfExactType(); 83 | if (scope == null) return null; 84 | return scope.state; 85 | } 86 | } 87 | 88 | class RouteState extends ChangeNotifier { 89 | final RouteBase route; 90 | final GlobalRouteState _globalRouteState; 91 | 92 | RouteState(this.route, GlobalRouteState globalState) 93 | : _globalRouteState = globalState; 94 | 95 | void goTo(String path) { 96 | _globalRouteState.goTo(path, parentRoute: route); 97 | } 98 | 99 | void pop() { 100 | _globalRouteState.pop(); 101 | } 102 | 103 | Map get queryParameters => 104 | _globalRouteState.match.parameters.query; 105 | 106 | Map get pathParameters => 107 | _globalRouteState.match.parameters.path; 108 | 109 | RouteBase? get activeChild { 110 | final routes = _globalRouteState.match.routes; 111 | 112 | final index = routes.indexOf(route); 113 | if (index < 0) { 114 | throw Exception('Route not found in global route state: $route'); 115 | } 116 | 117 | final nextIndex = index + 1; 118 | if (nextIndex >= routes.length) { 119 | return null; 120 | } 121 | 122 | return routes[nextIndex]; 123 | } 124 | 125 | static RouteState of(BuildContext context) { 126 | final routeStateScope = 127 | context.dependOnInheritedWidgetOfExactType(); 128 | if (routeStateScope == null) throw ('No RouteState in scope!'); 129 | return routeStateScope.state; 130 | } 131 | } 132 | 133 | class InitialRouteNotFoundError extends Error { 134 | final String initialRoute; 135 | 136 | InitialRouteNotFoundError(this.initialRoute); 137 | 138 | @override 139 | String toString() => 'No routes found for initial route: "$initialRoute"'; 140 | } 141 | -------------------------------------------------------------------------------- /lib/src/tree.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:path/path.dart' as p; 6 | import 'package:go_router_prototype/src/parameters.dart'; 7 | 8 | import 'match.dart'; 9 | import 'matching.dart'; 10 | import 'route.dart'; 11 | 12 | class RouteTree { 13 | List routes; 14 | 15 | RouteTree(this.routes) { 16 | _validate(); 17 | } 18 | 19 | RouteMatch get(String path, 20 | {RouteBase? parentRoute, RouteMatch? previousMatch}) { 21 | // If this is a relative path, search the children for a match. 22 | if (!path.startsWith('/')) { 23 | final children = parentRoute?.routes ?? []; 24 | for (var i = 0; i < children.length; i++) { 25 | final child = children[i]; 26 | if (hasMatch(child.path, path)) { 27 | final ancestors = 28 | _getAncestors(parentRoute!, previousMatch: previousMatch); 29 | final matchedRoutes = [...ancestors, child]; 30 | 31 | // Use the same parameters as the current match, but any routes that 32 | // are no longer matched need to have their parameters removed. 33 | Parameters parameters = extractParameters(child.path, path); 34 | if (previousMatch != null) { 35 | parameters = 36 | _removeOldParameters(previousMatch, matchedRoutes, parameters); 37 | } 38 | 39 | return _includeDefaultChild( 40 | RouteMatch(routes: matchedRoutes, parameters: parameters)); 41 | } 42 | } 43 | throw ('No relative route for $path found as a child of route: $parentRoute'); 44 | } else { 45 | return _getRecursive([], routes, path); 46 | } 47 | } 48 | 49 | RouteMatch pop(RouteMatch previousMatch) { 50 | final lastRoute = previousMatch.getLast(); 51 | if (lastRoute == null) { 52 | throw RouteStateError( 53 | 'Unable to call pop() because no matching routes were found'); 54 | } 55 | 56 | final newRoutes = _getAncestors(lastRoute, 57 | inclusive: false, previousMatch: previousMatch); 58 | final newParams = _removeOldParameters( 59 | previousMatch, newRoutes, previousMatch.parameters); 60 | return RouteMatch(routes: newRoutes, parameters: newParams); 61 | } 62 | 63 | RouteMatch _includeDefaultChild(RouteMatch match) { 64 | final lastRoute = match.getLast(); 65 | if (lastRoute == null) return match; 66 | final defaultChild = 67 | lastRoute is ShellRoute ? lastRoute.defaultRoute : null; 68 | if (defaultChild != null) { 69 | return get(defaultChild, parentRoute: lastRoute); 70 | } 71 | return match; 72 | } 73 | 74 | Parameters _removeOldParameters( 75 | RouteMatch oldMatch, List newRoutes, Parameters newParams) { 76 | // Don't preserve query parameters when the route is relative. 77 | final newQueryParams = {...oldMatch.parameters.query, ...newParams.query}; 78 | final newPathParams = {...oldMatch.parameters.path, ...newParams.path}; 79 | final oldRoutesLength = oldMatch.routes.length; 80 | final newRoutesLength = newRoutes.length; 81 | 82 | if (newRoutesLength < oldRoutesLength) { 83 | for (var i = newRoutesLength; i < oldRoutesLength; i++) { 84 | final route = oldMatch.routes[i]; 85 | final paramsToRemove = parseParameterNames(route.path); 86 | 87 | for (var paramToRemove in paramsToRemove) { 88 | if (newPathParams.containsKey(paramToRemove)) { 89 | newPathParams.remove(paramToRemove); 90 | } 91 | } 92 | } 93 | } 94 | return Parameters(newPathParams, newQueryParams); 95 | } 96 | 97 | // Checks that all route paths are correct, according to these rules: 98 | // - Top-level routes start with '/' 99 | // - Sub-routes *don't* start with '/') 100 | void _validate() { 101 | _validateRecursive(routes, true); 102 | } 103 | 104 | void _validateRecursive(List routes, bool topLevel) { 105 | // A '/' route is required because PlatformRouteInformationProvider uses 106 | // WidgetsBinding.instance!.window.defaultRouteName, which will be '/' if no 107 | // default route was requested. 108 | bool foundDefaultRoute = false; 109 | for (var route in routes) { 110 | if (topLevel && route.path == '/') { 111 | foundDefaultRoute = true; 112 | } 113 | if (topLevel && !route.path.startsWith('/')) { 114 | throw RouteConfigurationError( 115 | 'Top-level paths must start with "/"', route); 116 | } else if (!topLevel && route.path.startsWith('/')) { 117 | throw RouteConfigurationError( 118 | 'Sub-route paths cannot start with "/"', route); 119 | } 120 | _validateRecursive(route.routes, false); 121 | } 122 | 123 | if (topLevel && !foundDefaultRoute) { 124 | throw RouteConfigurationError( 125 | 'A top-level route with the path "/" is required'); 126 | } 127 | } 128 | 129 | /// Recursively searches for a match. [prefixes] is the list of 130 | /// parent Routes that have matched so far. 131 | RouteMatch _getRecursive( 132 | List prefixes, List current, String path) { 133 | for (var route in current) { 134 | if (hasExactMatch(route.path, path)) { 135 | prefixes.add(route); 136 | final parameters = extractParameters(route.path, path); 137 | return _includeDefaultChild( 138 | RouteMatch(routes: prefixes, parameters: parameters)); 139 | } 140 | } 141 | 142 | for (var route in current) { 143 | final prefixStrings = []; 144 | for (var prefix in prefixes) { 145 | prefixStrings.add(prefix.path); 146 | } 147 | 148 | final routePathWithPrefixes = route.path.startsWith('/') 149 | ? route.path 150 | : p.joinAll([...prefixStrings, route.path]); 151 | 152 | if (hasMatch(routePathWithPrefixes, path)) { 153 | prefixes.add(route); 154 | final childMatch = _getRecursive(prefixes, route.routes, path); 155 | if (childMatch.routes.isNotEmpty) { 156 | // More of the route was matched, return that match instead 157 | return childMatch; 158 | } 159 | 160 | // This is a relative route and no children matched, so return this 161 | // as the result. 162 | final parameters = extractParameters(routePathWithPrefixes, path); 163 | return _includeDefaultChild( 164 | RouteMatch(routes: prefixes, parameters: parameters)); 165 | } 166 | } 167 | return RouteMatch(routes: [], parameters: Parameters.empty()); 168 | } 169 | 170 | List _getAncestors(RouteBase routeToFind, 171 | {RouteMatch? previousMatch, bool inclusive = true}) { 172 | return _getAncestorsRecursive( 173 | routes, routeToFind, [], inclusive, previousMatch); 174 | } 175 | 176 | List _getAncestorsRecursive( 177 | List current, 178 | RouteBase routeToFind, 179 | List prefixes, 180 | bool inclusive, 181 | RouteMatch? previousMatch) { 182 | final currentPathTemplate = p.joinAll(prefixes.map((r) => r.path)); 183 | bool routeHasCorrectPrefix = previousMatch == null 184 | ? true 185 | : hasMatch(currentPathTemplate, previousMatch.path); 186 | for (var route in current) { 187 | if (route == routeToFind && routeHasCorrectPrefix) { 188 | return [ 189 | ...prefixes, 190 | if (inclusive) routeToFind, 191 | ]; 192 | } 193 | final searchedChildren = _getAncestorsRecursive(route.routes, routeToFind, 194 | [...prefixes, route], inclusive, previousMatch); 195 | if (searchedChildren.isNotEmpty) { 196 | return searchedChildren; 197 | } 198 | } 199 | return []; 200 | } 201 | } 202 | 203 | class RouteConfigurationError extends Error { 204 | final String message; 205 | final RouteBase? route; 206 | 207 | RouteConfigurationError(this.message, [this.route]); 208 | 209 | @override 210 | String toString() => route == null ? message : '$message: "${route!.path}"'; 211 | } 212 | 213 | class RouteStateError extends Error { 214 | final String message; 215 | 216 | RouteStateError(this.message); 217 | 218 | @override 219 | String toString() => message; 220 | } 221 | -------------------------------------------------------------------------------- /lib/src/typedefs.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/widgets.dart'; 6 | 7 | import 'match.dart'; 8 | 9 | typedef StackedRouteBuilder = Widget Function( 10 | BuildContext context, 11 | ); 12 | 13 | typedef ShellRouteBuilder = Widget Function( 14 | BuildContext context, 15 | Widget child, 16 | ); 17 | 18 | typedef NavigatorRouteBuilder = Widget Function( 19 | BuildContext context, 20 | ); 21 | 22 | typedef Redirect = Future Function(RouteMatch routeState); 23 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: go_router_prototype 2 | description: GoRouter API prototype 3 | version: 0.1.0 4 | homepage: https://github.com/johnpryan/go_router_prototype 5 | 6 | environment: 7 | sdk: ">=2.16.1 <3.0.0" 8 | flutter: ">=1.17.0" 9 | 10 | dependencies: 11 | flutter: 12 | sdk: flutter 13 | quiver: ^3.0.1 14 | path_to_regexp: ^0.4.0 15 | collection: ^1.15.0 16 | path: ^1.8.0 17 | 18 | dev_dependencies: 19 | flutter_test: 20 | sdk: flutter 21 | flutter_lints: ^1.0.0 22 | flutter: 23 | -------------------------------------------------------------------------------- /test/builder_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:flutter_test/flutter_test.dart'; 7 | import 'package:go_router_prototype/src/delegate.dart'; 8 | import 'package:go_router_prototype/src/match.dart'; 9 | import 'package:go_router_prototype/src/parameters.dart'; 10 | import 'package:go_router_prototype/src/parser.dart'; 11 | import 'package:go_router_prototype/src/route.dart'; 12 | import 'package:go_router_prototype/src/state.dart'; 13 | 14 | void main() { 15 | group('buildRoute', () { 16 | testWidgets( 17 | 'Configures the Navigator based on the match in GlobalRouteState', 18 | (WidgetTester tester) async { 19 | final routeB = 20 | StackedRoute(path: 'b', builder: (_) => const Text('Screen B')); 21 | final routeA = StackedRoute( 22 | path: '/', builder: (_) => const Text('Screen B'), routes: [routeB]); 23 | final routes = [routeA]; 24 | 25 | final routeMatch = RouteMatch( 26 | routes: [routeA, routeB], 27 | parameters: Parameters.empty(), 28 | ); 29 | 30 | final globalRouteState = GlobalRouteState(routes); 31 | final routerDelegate = GoRouterDelegate.withState(globalRouteState); 32 | 33 | await tester.pumpWidget( 34 | _TestWidget( 35 | informationProvider: _TestRouteInformationProvider(), 36 | routerDelegate: routerDelegate, 37 | ), 38 | ); 39 | 40 | await globalRouteState.setMatch(routeMatch); 41 | await tester.pumpAndSettle(); 42 | 43 | expect(find.text('Screen B'), findsOneWidget); 44 | }); 45 | }); 46 | } 47 | 48 | class _TestWidget extends StatefulWidget { 49 | final GoRouterDelegate routerDelegate; 50 | final GoRouteInformationParser routeInformationParser; 51 | final _TestRouteInformationProvider informationProvider; 52 | 53 | _TestWidget( 54 | {Key? key, 55 | required this.informationProvider, 56 | required this.routerDelegate}) 57 | : routeInformationParser = GoRouteInformationParser(), 58 | super(key: key); 59 | 60 | @override 61 | State<_TestWidget> createState() => _TestWidgetState(); 62 | } 63 | 64 | class _TestWidgetState extends State<_TestWidget> { 65 | @override 66 | Widget build(BuildContext context) { 67 | return MaterialApp.router( 68 | routerDelegate: widget.routerDelegate, 69 | routeInformationParser: widget.routeInformationParser, 70 | routeInformationProvider: widget.informationProvider, 71 | ); 72 | } 73 | } 74 | 75 | class _TestRouteInformationProvider extends RouteInformationProvider 76 | with ChangeNotifier { 77 | RouteInformation _value; 78 | 79 | _TestRouteInformationProvider({String initialRoute = '/'}) 80 | : _value = RouteInformation(location: initialRoute); 81 | 82 | @override 83 | RouteInformation get value => _value; 84 | 85 | set value(RouteInformation value) { 86 | if (value == _value) { 87 | return; 88 | } 89 | _value = value; 90 | notifyListeners(); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /test/helpers.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:go_router_prototype/src/delegate.dart'; 7 | import 'package:go_router_prototype/src/parser.dart'; 8 | import 'package:go_router_prototype/go_router_prototype.dart'; 9 | 10 | Widget emptyBuilder(context) => const EmptyWidget(); 11 | 12 | Widget emptyShellBuilder(context, child) => child; 13 | 14 | class EmptyWidget extends StatelessWidget { 15 | const EmptyWidget({Key? key}) : super(key: key); 16 | 17 | @override 18 | Widget build(BuildContext context) => const Placeholder(); 19 | } 20 | 21 | class TestWidget extends StatefulWidget { 22 | final GoRouterDelegate routerDelegate; 23 | final GoRouteInformationParser routeInformationParser; 24 | final TestRouteInformationProvider informationProvider; 25 | 26 | TestWidget({ 27 | Key? key, 28 | required List routes, 29 | TestRouteInformationProvider? informationProvider, 30 | GlobalRouteState? routeState, 31 | String initialRoute = '/', 32 | }) : routerDelegate = routeState == null 33 | ? GoRouterDelegate(routes) 34 | : GoRouterDelegate.withState(routeState), 35 | routeInformationParser = GoRouteInformationParser(), 36 | informationProvider = informationProvider ?? 37 | TestRouteInformationProvider(initialRoute: initialRoute), 38 | super(key: key); 39 | 40 | @override 41 | State createState() => _TestWidgetState(); 42 | } 43 | 44 | class _TestWidgetState extends State { 45 | @override 46 | Widget build(BuildContext context) { 47 | return MaterialApp.router( 48 | routerDelegate: widget.routerDelegate, 49 | routeInformationParser: widget.routeInformationParser, 50 | routeInformationProvider: widget.informationProvider, 51 | ); 52 | } 53 | } 54 | 55 | class TestRouteInformationProvider extends RouteInformationProvider 56 | with ChangeNotifier { 57 | RouteInformation _value; 58 | 59 | TestRouteInformationProvider({String initialRoute = '/'}) 60 | : _value = RouteInformation(location: initialRoute); 61 | 62 | @override 63 | RouteInformation get value => _value; 64 | 65 | set value(RouteInformation value) { 66 | if (value == _value) { 67 | return; 68 | } 69 | _value = value; 70 | notifyListeners(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /test/matcher_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter_test/flutter_test.dart'; 6 | import 'package:go_router_prototype/src/matching.dart'; 7 | import 'package:go_router_prototype/src/parameters.dart'; 8 | 9 | void main() { 10 | group('Matching helpers', () { 11 | test('hasMatch', () { 12 | expect(hasMatch('/user/:id', '/user/1'), true); 13 | expect(hasMatch('/', '/user/1'), true); 14 | expect(hasMatch('/user/:id', '/user/1/order/3'), true); 15 | expect(hasMatch('/user', '/user/1'), true); 16 | expect(hasMatch('user', 'user/1'), true); 17 | expect(hasMatch('user/:id', 'user/1'), true); 18 | expect(hasMatch('/user/:id', '/user/1/suffix'), true); 19 | }); 20 | 21 | test('hasExactMatch', () { 22 | expect(hasExactMatch('/user/:id', '/user/1'), true); 23 | expect(hasExactMatch('/', '/user/1'), false); 24 | expect(hasExactMatch('/user/:id', '/user/1/order/3'), false); 25 | expect(hasExactMatch('/user', '/user/1'), false); 26 | expect(hasExactMatch('user', 'user/1'), false); 27 | expect(hasExactMatch('user/:id', 'user/1'), true); 28 | expect( 29 | hasExactMatch('Left Hand of Darkness', 30 | Uri.decodeComponent('Left%20Hand%20of%20Darkness')), 31 | true); 32 | expect(hasExactMatch('/', '/?q=foo'), true); 33 | }); 34 | 35 | test('extractParameters', () { 36 | expect(extractParameters('/', '/'), Parameters({}, {})); 37 | expect(extractParameters('/user/:id', '/user/1'), 38 | Parameters({'id': '1'}, {})); 39 | expect(extractParameters('/user/:id', '/user'), Parameters({}, {})); 40 | expect(extractParameters('/user/:id', '/user/1/order/3'), 41 | Parameters({'id': '1'}, {})); 42 | expect(extractParameters('/user/:id/order/:orderId', '/user/1/order/3'), 43 | Parameters({'id': '1', 'orderId': '3'}, {})); 44 | expect( 45 | extractParameters('user/:id', 'user/1'), Parameters({'id': '1'}, {})); 46 | }); 47 | 48 | test('fillParameters', () { 49 | expect( 50 | fillParameters('/user/:id', Parameters({'id': '1'}, {})), '/user/1'); 51 | expect(fillParameters('/search', Parameters({}, {'q': 'dog'})), 52 | '/search?q=dog'); 53 | expect(fillParameters('/foo.txt', Parameters({}, {})), '/foo.txt'); 54 | }); 55 | 56 | test('parseParameterNames', () { 57 | expect(parseParameterNames('user/:id'), ['id']); 58 | }); 59 | }); 60 | } 61 | -------------------------------------------------------------------------------- /test/redirect_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/foundation.dart'; 2 | import 'package:flutter/material.dart'; 3 | import 'package:flutter_test/flutter_test.dart'; 4 | import 'package:go_router_prototype/go_router_prototype.dart'; 5 | 6 | import 'helpers.dart'; 7 | 8 | void main() { 9 | group('Redirect', () { 10 | testWidgets('redirects to a relative path at startup', 11 | (WidgetTester tester) async { 12 | final routes = [ 13 | ShellRoute( 14 | path: '/', 15 | redirect: (match) { 16 | return SynchronousFuture('a'); 17 | }, 18 | builder: (_, child) => child, 19 | routes: [ 20 | StackedRoute( 21 | path: 'a', 22 | builder: (context) { 23 | return const AScreen(); 24 | }, 25 | ), 26 | ], 27 | ), 28 | ]; 29 | await tester.pumpWidget( 30 | TestWidget( 31 | routes: routes, 32 | initialRoute: '/', 33 | ), 34 | ); 35 | await tester.pumpAndSettle(); 36 | expect(find.text('Screen A'), findsOneWidget); 37 | }); 38 | 39 | testWidgets('Redirects multiple times', (WidgetTester tester) async { 40 | final routes = [ 41 | ShellRoute( 42 | path: '/', 43 | redirect: (match) { 44 | return SynchronousFuture('a'); 45 | }, 46 | builder: (_, child) => child, 47 | routes: [ 48 | StackedRoute( 49 | path: 'a', 50 | redirect: (match) { 51 | return SynchronousFuture('b'); 52 | }, 53 | builder: (context) { 54 | return const AScreen(); 55 | }, 56 | routes: [ 57 | StackedRoute( 58 | path: 'b', 59 | builder: (context) { 60 | return const BScreen(); 61 | }, 62 | ), 63 | ], 64 | ), 65 | ], 66 | ), 67 | ]; 68 | 69 | await tester.pumpWidget( 70 | TestWidget( 71 | routes: routes, 72 | initialRoute: '/', 73 | ), 74 | ); 75 | 76 | await tester.pumpAndSettle(); 77 | expect(find.text('Screen B'), findsOneWidget); 78 | }); 79 | 80 | testWidgets('Avoids infinite redirects', (WidgetTester tester) async { 81 | final routes = [ 82 | ShellRoute( 83 | path: '/', 84 | redirect: (match) { 85 | return SynchronousFuture('/a'); 86 | }, 87 | builder: (_, child) => child, 88 | routes: [ 89 | StackedRoute( 90 | path: 'a', 91 | redirect: (match) { 92 | return SynchronousFuture('/b'); 93 | }, 94 | builder: (context) { 95 | return const AScreen(); 96 | }, 97 | ), 98 | StackedRoute( 99 | path: 'b', 100 | redirect: (match) { 101 | return SynchronousFuture('/a'); 102 | }, 103 | builder: (context) { 104 | return const BScreen(); 105 | }, 106 | ), 107 | ], 108 | ), 109 | ]; 110 | 111 | await tester.pumpWidget( 112 | TestWidget( 113 | routes: routes, 114 | initialRoute: '/', 115 | ), 116 | ); 117 | 118 | await tester.pumpAndSettle(); 119 | expect(find.text('Screen B'), findsOneWidget); 120 | }, skip: true); 121 | }); 122 | } 123 | 124 | class HomeScreen extends StatelessWidget { 125 | const HomeScreen({Key? key}) : super(key: key); 126 | 127 | @override 128 | Widget build(BuildContext context) { 129 | return const Text('Home'); 130 | } 131 | } 132 | 133 | class AScreen extends StatelessWidget { 134 | const AScreen({Key? key}) : super(key: key); 135 | 136 | @override 137 | Widget build(BuildContext context) { 138 | return const Text('Screen A'); 139 | } 140 | } 141 | 142 | class BScreen extends StatelessWidget { 143 | const BScreen({Key? key}) : super(key: key); 144 | 145 | @override 146 | Widget build(BuildContext context) { 147 | return const Text('Screen B'); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /test/route_match_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter_test/flutter_test.dart'; 6 | import 'package:go_router_prototype/src/match.dart'; 7 | import 'package:go_router_prototype/src/parameters.dart'; 8 | import 'package:go_router_prototype/src/route.dart'; 9 | 10 | import 'helpers.dart'; 11 | 12 | void main() { 13 | group('RouteMatch.currentRoutePath', () { 14 | test('combines the paths for the matched routes', () { 15 | final match = RouteMatch( 16 | routes: [ 17 | StackedRoute(path: '/', builder: emptyBuilder), 18 | StackedRoute(path: 'a', builder: emptyBuilder), 19 | StackedRoute(path: 'b', builder: emptyBuilder), 20 | ], 21 | parameters: Parameters({}, {}), 22 | ); 23 | 24 | expect(match.path, '/a/b'); 25 | }); 26 | test('includes parameters', () { 27 | final match = RouteMatch( 28 | routes: [ 29 | StackedRoute(path: '/', builder: emptyBuilder), 30 | StackedRoute(path: 'user/:id', builder: emptyBuilder), 31 | ], 32 | parameters: Parameters({'id': '123'}, {}), 33 | ); 34 | 35 | expect(match.path, '/user/123'); 36 | }); 37 | 38 | test('combines the paths for the matched routes', () { 39 | final match = RouteMatch( 40 | routes: [ 41 | ShellRoute(path: '/', builder: emptyShellBuilder), 42 | NestedStackRoute(path: 'a', builder: emptyBuilder), 43 | StackedRoute(path: 'b', builder: emptyBuilder), 44 | ], 45 | parameters: Parameters({}, {}), 46 | ); 47 | 48 | expect(match.path, '/a/b'); 49 | }); 50 | 51 | test('combines the paths for the matched routes', () { 52 | final match = RouteMatch( 53 | routes: [ 54 | ShellRoute(path: '/', builder: emptyShellBuilder), 55 | ShellRoute(path: 'Documents', builder: emptyShellBuilder), 56 | ShellRoute(path: 'Books', builder: emptyShellBuilder), 57 | ShellRoute(path: 'Left_Hand.epub', builder: emptyShellBuilder), 58 | ], 59 | parameters: Parameters({}, {}), 60 | ); 61 | 62 | expect(match.path, '/Documents/Books/Left_Hand.epub'); 63 | }); 64 | 65 | group('prefix operations', () { 66 | RouteMatch _buildMatch(List paths) { 67 | return RouteMatch( 68 | routes: [ 69 | ...paths.map((p) => StackedRoute(path: p, builder: emptyBuilder)) 70 | ], 71 | parameters: Parameters({}, {}), 72 | ); 73 | } 74 | 75 | final match1 = _buildMatch(['/', 'Documents']); 76 | final match2 = _buildMatch(['/', 'Documents', 'Books', 'book1']); 77 | final match3 = _buildMatch(['/', 'Documents', 'Pictures']); 78 | 79 | test('isPrefixOf', () { 80 | expect(match1.isPrefixOf(match2), true); 81 | expect(match1.isPrefixOf(match1), true); 82 | expect(match3.isPrefixOf(match1), false); 83 | }); 84 | 85 | test('getMatchingPrefixIndex', () { 86 | expect(match1.getMatchingPrefixIndex(match1), 2); 87 | expect(match1.getMatchingPrefixIndex(match2), 2); 88 | expect(match2.getMatchingPrefixIndex(match3), 2); 89 | expect(match3.getMatchingPrefixIndex(match1), -1); 90 | }); 91 | }); 92 | }); 93 | } 94 | -------------------------------------------------------------------------------- /test/route_state_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/material.dart'; 6 | import 'package:flutter_test/flutter_test.dart'; 7 | import 'package:go_router_prototype/src/delegate.dart'; 8 | import 'package:go_router_prototype/src/parser.dart'; 9 | import 'package:go_router_prototype/go_router_prototype.dart'; 10 | 11 | void main() { 12 | group('RouteState', () { 13 | testWidgets('.of() Returns a route state object', 14 | (WidgetTester tester) async { 15 | late final BuildContext childContext; 16 | final routes = [ 17 | StackedRoute( 18 | path: '/', 19 | builder: (context) => Builder( 20 | builder: (BuildContext context) { 21 | childContext = context; 22 | return const Placeholder(); 23 | }, 24 | ), 25 | ), 26 | ]; 27 | 28 | await tester.pumpWidget( 29 | _TestApp( 30 | routes: routes, 31 | ), 32 | ); 33 | 34 | expect(RouteState.of(childContext), isNotNull); 35 | }); 36 | 37 | testWidgets('goTo() Navigates to the correct screen', 38 | (WidgetTester tester) async { 39 | late final BuildContext childContext; 40 | final routes = [ 41 | StackedRoute( 42 | path: '/', 43 | builder: (context) { 44 | return Builder( 45 | builder: (BuildContext context) { 46 | childContext = context; 47 | return const Text('Home'); 48 | }, 49 | ); 50 | }, 51 | ), 52 | StackedRoute( 53 | path: '/a', 54 | builder: (context) { 55 | return const Text('Screen A'); 56 | }, 57 | ), 58 | ]; 59 | 60 | await tester.pumpWidget( 61 | _TestApp( 62 | routes: routes, 63 | ), 64 | ); 65 | 66 | expect(find.text('Home'), findsOneWidget); 67 | final routeState = RouteState.of(childContext); 68 | routeState.goTo('/a'); 69 | await tester.pumpAndSettle(); 70 | expect(find.text('Screen A'), findsOneWidget); 71 | }); 72 | 73 | testWidgets('pop() Navigates to the correct screen', 74 | (WidgetTester tester) async { 75 | BuildContext? childContext; 76 | final routes = [ 77 | StackedRoute( 78 | path: '/', 79 | builder: (context) { 80 | return Builder( 81 | builder: (BuildContext context) { 82 | childContext ??= context; 83 | return const Text('Home'); 84 | }, 85 | ); 86 | }, 87 | routes: [ 88 | StackedRoute( 89 | path: 'a', 90 | builder: (context) { 91 | return const Text('Screen A'); 92 | }, 93 | ), 94 | ], 95 | ), 96 | ]; 97 | 98 | await tester.pumpWidget( 99 | _TestApp( 100 | routes: routes, 101 | ), 102 | ); 103 | 104 | expect(find.text('Home'), findsOneWidget); 105 | final routeState = RouteState.of(childContext!); 106 | 107 | routeState.goTo('/a'); 108 | await tester.pumpAndSettle(); 109 | expect(find.text('Screen A'), findsOneWidget); 110 | 111 | routeState.pop(); 112 | await tester.pumpAndSettle(); 113 | expect(find.text('Home'), findsOneWidget); 114 | }); 115 | 116 | testWidgets( 117 | 'Navigates to the correct screen when provided with a relative route path', 118 | (WidgetTester tester) async { 119 | BuildContext? rootContext; 120 | BuildContext? aContext; 121 | BuildContext? bContext; 122 | final routes = [ 123 | StackedRoute( 124 | path: '/', 125 | builder: (context) { 126 | rootContext ??= context; 127 | return const Text('Home'); 128 | }, 129 | routes: [ 130 | StackedRoute( 131 | path: 'a', 132 | builder: (context) { 133 | aContext ??= context; 134 | return const Text('Screen A'); 135 | }, 136 | routes: [ 137 | StackedRoute( 138 | path: 'b/:id', 139 | builder: (context) { 140 | bContext ??= context; 141 | return const Text('Screen B'); 142 | }, 143 | ), 144 | ], 145 | ), 146 | ], 147 | ), 148 | ]; 149 | 150 | await tester.pumpWidget( 151 | _TestApp( 152 | routes: routes, 153 | ), 154 | ); 155 | 156 | expect(find.text('Home'), findsOneWidget); 157 | expect(GlobalRouteState.of(rootContext!)!.match.routes, hasLength(1)); 158 | 159 | // Navigate to 'a' 160 | var routeState = RouteState.of(rootContext!); 161 | expect(routeState, isNotNull); 162 | routeState.goTo('a'); 163 | await tester.pumpAndSettle(); 164 | expect(find.text('Screen A'), findsOneWidget); 165 | expect(GlobalRouteState.of(aContext!)!.match.routes, hasLength(2)); 166 | 167 | // Navigate to 'b' 168 | routeState = RouteState.of(aContext!); 169 | expect(routeState, isNotNull); 170 | routeState.goTo('b/123'); 171 | await tester.pumpAndSettle(); 172 | expect(find.text('Screen B'), findsOneWidget); 173 | expect(GlobalRouteState.of(bContext!)!.match.routes, hasLength(3)); 174 | expect(RouteState.of(bContext!).pathParameters, hasLength(1)); 175 | }); 176 | 177 | testWidgets('Relative route paths include path parameters', 178 | (WidgetTester tester) async { 179 | BuildContext? rootContext; 180 | BuildContext? aContext; 181 | final routes = [ 182 | StackedRoute( 183 | path: '/', 184 | builder: (context) { 185 | rootContext ??= context; 186 | return const Text('Home'); 187 | }, 188 | routes: [ 189 | StackedRoute( 190 | path: 'a/:id', 191 | builder: (context) { 192 | aContext ??= context; 193 | return const Text('Screen A'); 194 | }, 195 | ), 196 | ], 197 | ), 198 | ]; 199 | 200 | await tester.pumpWidget( 201 | _TestApp( 202 | routes: routes, 203 | ), 204 | ); 205 | 206 | expect(find.text('Home'), findsOneWidget); 207 | expect(GlobalRouteState.of(rootContext!)!.match.routes, hasLength(1)); 208 | 209 | // Navigate to 'a' 210 | var routeState = RouteState.of(rootContext!); 211 | expect(routeState, isNotNull); 212 | routeState.goTo('a/123'); 213 | await tester.pumpAndSettle(); 214 | expect(find.text('Screen A'), findsOneWidget); 215 | expect(GlobalRouteState.of(aContext!)!.match.routes, hasLength(2)); 216 | expect(RouteState.of(aContext!).pathParameters, hasLength(1)); 217 | }); 218 | 219 | testWidgets( 220 | 'Relative route paths include path parameters of the parent route', 221 | (WidgetTester tester) async { 222 | BuildContext? rootContext; 223 | BuildContext? aContext; 224 | final routes = [ 225 | StackedRoute( 226 | path: '/', 227 | builder: (context) { 228 | rootContext ??= context; 229 | return const Text('Home'); 230 | }, 231 | routes: [ 232 | StackedRoute( 233 | path: 'a/:id', 234 | builder: (context) { 235 | aContext ??= context; 236 | return const Text('Screen A'); 237 | }, 238 | routes: [ 239 | StackedRoute( 240 | path: 'details', 241 | builder: (context) { 242 | return const Text('Screen A Details'); 243 | }), 244 | ], 245 | ), 246 | ], 247 | ), 248 | ]; 249 | 250 | await tester.pumpWidget( 251 | _TestApp( 252 | routes: routes, 253 | ), 254 | ); 255 | 256 | expect(find.text('Home'), findsOneWidget); 257 | expect(GlobalRouteState.of(rootContext!)!.match.routes, hasLength(1)); 258 | 259 | // Navigate to 'a' 260 | var routeState = RouteState.of(rootContext!); 261 | expect(routeState, isNotNull); 262 | routeState.goTo('a/123'); 263 | 264 | await tester.pumpAndSettle(); 265 | expect(find.text('Screen A'), findsOneWidget); 266 | expect(GlobalRouteState.of(aContext!)!.match.routes, hasLength(2)); 267 | expect(RouteState.of(aContext!).pathParameters, hasLength(1)); 268 | 269 | routeState = RouteState.of(aContext!); 270 | expect(routeState, isNotNull); 271 | routeState.goTo('details'); 272 | 273 | await tester.pumpAndSettle(); 274 | expect(find.text('Screen A Details'), findsOneWidget); 275 | expect(GlobalRouteState.of(aContext!)!.match.routes, hasLength(3)); 276 | expect(RouteState.of(aContext!).pathParameters, hasLength(1)); 277 | }); 278 | }); 279 | } 280 | 281 | class _TestApp extends StatelessWidget { 282 | final List routes; 283 | 284 | const _TestApp({required this.routes, Key? key}) : super(key: key); 285 | 286 | @override 287 | Widget build(BuildContext context) { 288 | return MaterialApp.router( 289 | routerDelegate: GoRouterDelegate(routes), 290 | routeInformationParser: GoRouteInformationParser(), 291 | ); 292 | } 293 | } 294 | -------------------------------------------------------------------------------- /test/route_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter_test/flutter_test.dart'; 6 | import 'package:go_router_prototype/src/route.dart'; 7 | 8 | import 'helpers.dart'; 9 | 10 | void main() { 11 | group('Route', () { 12 | test('equality', () { 13 | final route = StackedRoute(path: '/', builder: emptyBuilder); 14 | final route2 = StackedRoute(path: '/', builder: emptyBuilder); 15 | expect(route, equals(route2)); 16 | }); 17 | 18 | test('routes with different children are not equal', () { 19 | final route = StackedRoute( 20 | path: '/', 21 | builder: emptyBuilder, 22 | routes: [ 23 | StackedRoute(path: 'a', builder: emptyBuilder), 24 | ], 25 | ); 26 | final route2 = StackedRoute(path: '/', builder: emptyBuilder); 27 | expect(route, isNot(equals(route2))); 28 | }); 29 | }); 30 | } 31 | -------------------------------------------------------------------------------- /test/tree_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Flutter team. All rights reserved. 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | import 'package:flutter/widgets.dart'; 6 | import 'package:flutter_test/flutter_test.dart'; 7 | import 'package:go_router_prototype/src/route.dart'; 8 | import 'package:go_router_prototype/src/state.dart'; 9 | import 'package:go_router_prototype/src/tree.dart'; 10 | 11 | import 'helpers.dart'; 12 | 13 | void main() { 14 | group('RouteTree', () { 15 | test('Looks up routes', () { 16 | final routes = [ 17 | StackedRoute( 18 | builder: emptyBuilder, 19 | path: '/', 20 | ), 21 | StackedRoute( 22 | builder: emptyBuilder, 23 | path: '/item/:id', 24 | ), 25 | ]; 26 | 27 | final tree = RouteTree(routes); 28 | 29 | var lookup = tree.get('/'); 30 | expect(lookup.routes, [routes.first]); 31 | 32 | lookup = tree.get('/item/1'); 33 | expect(lookup.routes, [routes[1]]); 34 | expect(lookup.parameters.path, {'id': '1'}); 35 | }); 36 | 37 | test('Looks up child routes', () { 38 | final routes = [ 39 | StackedRoute( 40 | builder: emptyBuilder, 41 | path: '/', 42 | routes: [ 43 | StackedRoute( 44 | builder: emptyBuilder, 45 | path: 'books/:bookId', 46 | ), 47 | StackedRoute( 48 | builder: emptyBuilder, 49 | path: 'profile', 50 | ), 51 | ], 52 | ), 53 | ]; 54 | 55 | final tree = RouteTree(routes); 56 | 57 | var lookup = tree.get('/'); 58 | expect(lookup.routes, isNotEmpty); 59 | expect(lookup.routes, hasLength(1)); 60 | 61 | lookup = tree.get('/books/234'); 62 | expect(lookup.routes, isNotEmpty); 63 | expect(lookup.routes, hasLength(2)); 64 | expect(lookup.parameters.path['bookId'], '234'); 65 | 66 | lookup = tree.get('/profile'); 67 | expect(lookup.routes, isNotEmpty); 68 | expect(lookup.routes, hasLength(2)); 69 | }); 70 | 71 | test('Throws when a sub-routes contains an absolute path', () { 72 | final routes = [ 73 | StackedRoute( 74 | builder: emptyBuilder, 75 | path: '/a', 76 | routes: [ 77 | StackedRoute( 78 | builder: emptyBuilder, 79 | path: '/b', 80 | ), 81 | ], 82 | ), 83 | ]; 84 | 85 | expect(() => RouteTree(routes), throwsA(isA())); 86 | }); 87 | test('Throws when there is no top-level path "/"', () { 88 | final routes = [ 89 | StackedRoute( 90 | path: '/a', 91 | builder: emptyBuilder, 92 | routes: [ 93 | StackedRoute( 94 | path: 'b', 95 | builder: emptyBuilder, 96 | ), 97 | ], 98 | ), 99 | StackedRoute( 100 | path: '/c', 101 | builder: emptyBuilder, 102 | ), 103 | ]; 104 | 105 | expect(() => RouteTree(routes), throwsA(isA())); 106 | }); 107 | 108 | test('Does not throw when top-level routes contain absolute paths', () { 109 | final routes = [ 110 | StackedRoute( 111 | builder: emptyBuilder, 112 | path: '/', 113 | ), 114 | StackedRoute( 115 | builder: emptyBuilder, 116 | path: '/a', 117 | ), 118 | StackedRoute( 119 | builder: emptyBuilder, 120 | path: '/b', 121 | ), 122 | ]; 123 | RouteTree(routes); 124 | }); 125 | 126 | test('Removes path parameters when pop() is called', () { 127 | final routes = [ 128 | StackedRoute( 129 | builder: emptyBuilder, 130 | path: '/', 131 | routes: [ 132 | StackedRoute( 133 | builder: emptyBuilder, 134 | path: 'books/:bookId', 135 | routes: [ 136 | StackedRoute( 137 | builder: emptyBuilder, 138 | path: 'details/:detailId', 139 | ), 140 | ], 141 | ), 142 | ], 143 | ), 144 | ]; 145 | final tree = RouteTree(routes); 146 | final match = tree.get('/books/123/details/456'); 147 | expect(match.parameters.path.keys.length, 2); 148 | 149 | final newMatch = tree.pop(match); 150 | expect(newMatch.parameters.path.keys.length, 1); 151 | }); 152 | 153 | test('pop() shows the correct route when there are duplicate paths', () { 154 | final bookRoute = StackedRoute( 155 | builder: (context) { 156 | final bookId = RouteState.of(context).pathParameters['bookId']!; 157 | return Text('Book $bookId'); 158 | }, 159 | path: 'book/:bookId', 160 | ); 161 | 162 | final routes = [ 163 | ShellRoute( 164 | builder: (context, child) => child, 165 | path: '/', 166 | routes: [ 167 | StackedRoute( 168 | builder: (context) => const Text('popular'), 169 | path: 'popular', 170 | routes: [ 171 | bookRoute, 172 | ], 173 | ), 174 | StackedRoute( 175 | builder: (context) => const Text('all'), 176 | path: 'all', 177 | routes: [ 178 | bookRoute, 179 | ], 180 | ), 181 | ], 182 | ), 183 | ]; 184 | final tree = RouteTree(routes); 185 | var match = tree.get('/all/book/123'); 186 | expect(match.routes, hasLength(3)); 187 | 188 | match = tree.pop(match); 189 | expect(match.routes, hasLength(2)); 190 | expect(match.getLast()!.path, 'all'); 191 | }); 192 | }); 193 | } 194 | 195 | class EmptyWidget extends StatelessWidget { 196 | const EmptyWidget({Key? key}) : super(key: key); 197 | 198 | @override 199 | Widget build(BuildContext context) => const Placeholder(); 200 | } 201 | --------------------------------------------------------------------------------