Repository: flutter
Issue: dependOnInheritedWidgetOfExactType didChangeDependencies dispose bug
Labels: framework,f: material design,a: error message,has reproducible steps,found in release: 2.2,team-design,triaged-design

<!-- Thank you for using Flutter!

     If you are looking for support, please check out our documentation
     or consider asking a question on Stack Overflow:
      * https://flutter.dev/
      * https://api.flutter.dev/
      * https://stackoverflow.com/questions/tagged/flutter?sort=frequent

     If you have found a bug or if our documentation doesn't have an answer
     to what you're looking for, then fill out the template below. Please read
     our guide to filing a bug first: https://flutter.dev/docs/resources/bug-reports
-->

## Steps to Reproduce

<!-- You must include full steps to reproduce so that we can reproduce the problem. -->

1. Run `flutter run`.
2. Update the main.dart as follows: https://gist.github.com/DavidHeiss/01c330eafd1ca16070711f26c4d15e97
3. press the icon button at the top

Minimal Example: https://dartpad.dev/01c330eafd1ca16070711f26c4d15e97?null_safety=true

**Expected results:** <!-- what did you want to see? -->
A message in the console that says "dispose works!"

**Actual results:** <!-- what did you see? -->
An exception get caught by the widgets library.

<details>
  <summary>Logs</summary>

<!--
      Run your application with `flutter run --verbose` and attach all the
      log output below between the lines with the backticks. If there is an
      exception, please see if the error message includes enough information
      to explain how to solve the issue.
-->

```
[  +50 ms] executing: uname -m
[  +24 ms] Exit code 0 from: uname -m
[        ] x86_64
[   +4 ms] executing: [/home/dh/development/flutter/] git -c
log.showSignature=false log -n 1 --pretty=format:%H
[   +6 ms] Exit code 0 from: git -c log.showSignature=false log -n 1
--pretty=format:%H
[        ] 02c026b03cd31dd3f867e5faeb7e104cce174c5f
[        ] executing: [/home/dh/development/flutter/] git tag --points-at
02c026b03cd31dd3f867e5faeb7e104cce174c5f
[  +10 ms] Exit code 0 from: git tag --points-at
02c026b03cd31dd3f867e5faeb7e104cce174c5f
[        ] 2.2.1
[   +4 ms] executing: [/home/dh/development/flutter/] git rev-parse --abbrev-ref
--symbolic @{u}
[   +4 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/stable
[        ] executing: [/home/dh/development/flutter/] git ls-remote --get-url
origin
[   +3 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[  +54 ms] Unable to locate an Android SDK.
[   +5 ms] executing: [/home/dh/development/flutter/] git rev-parse --abbrev-ref
HEAD
[   +4 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] stable
[  +42 ms] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping
update.
[        ] Artifact Instance of 'FlutterWebSdk' is not required, skipping
update.
[   +1 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping
update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping
update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required,
skipping update.
[  +48 ms] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping
update.
[   +1 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping
update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping
update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required,
skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required,
skipping update.
[  +54 ms] Skipping pub get: version match.
[  +79 ms] Generating
/mnt/2ead31d1-5582-465b-a3de-112f1a6e04ae/test/android/app/src/main/java/io/flut
ter/plugins/GeneratedPluginRegistrant.java
[ +110 ms] Launching lib/main.dart on Chrome in debug mode...
[  +98 ms] Updating assets
[  +54 ms] Waiting for connection from debug service on Chrome...
[  +60 ms] <- reset
[   +4 ms] /home/dh/development/flutter/bin/cache/dart-sdk/bin/dart
--disable-dart-dev
/home/dh/development/flutter/bin/cache/artifacts/engine/linux-x64/frontend_serve
r.dart.snapshot --sdk-root
/home/dh/development/flutter/bin/cache/flutter_web_sdk/ --incremental
--target=dartdevc --debugger-module-names --experimental-emit-debug-metadata
-DFLUTTER_WEB_AUTO_DETECT=true --output-dill
/tmp/flutter_tools.DJMFJA/flutter_tool.NRGMWS/app.dill --libraries-spec
file:///home/dh/development/flutter/bin/cache/flutter_web_sdk/libraries.json
--packages
/mnt/2ead31d1-5582-465b-a3de-112f1a6e04ae/test/.dart_tool/package_config.json
-Ddart.vm.profile=false -Ddart.vm.product=false --enable-asserts
--track-widget-creation --filesystem-root
/tmp/flutter_tools.DJMFJA/flutter_tools.RXPRDI --filesystem-scheme
org-dartlang-app --initialize-from-dill
build/b1b715402d823b7fd5c2b68d2edcb2ce.cache.dill.track.dill --platform
file:///home/dh/development/flutter/bin/cache/flutter_web_sdk/kernel/flutter_ddc
_sdk_sound.dill --sound-null-safety
[   +5 ms] <- compile org-dartlang-app:/web_entrypoint.dart
[+13951 ms] Waiting for connection from debug service on Chrome... (completed in 14.0s)
[        ] Synced 28.2MB.
[        ] <- accept
[        ] Caching compiled dill
[  +63 ms] Using Google Chrome 91.0.4472.77 

[ +279 ms] [CHROME]:
[        ] [CHROME]:DevTools listening on ws://127.0.0.1:33933/devtools/browser/9be3a1f5-61e7-4a54-a127-27ca013c7b5b
[ +256 ms] DwdsInjector: Received request for entrypoint at http://localhost:41239/main_module.bootstrap.js
[   +5 ms] MetadataProvider: Loading debug metadata...
[  +13 ms] MetadataProvider: Loaded debug metadata (sound null safety)
[   +6 ms] DwdsInjector: Injected debugging metadata for entrypoint at http://localhost:41239/main_module.bootstrap.js
[+1246 ms] ChromeProxyService: Initializing expression compiler for main_module.bootstrap.js with sound null safety: true
[  +51 ms] DevHandler: Debug service listening on ws://127.0.0.1:46215/Gf2rsDmiuAU=/ws

[  +17 ms] This app is linked to the debug service: ws://127.0.0.1:46215/Gf2rsDmiuAU=/ws
[   +5 ms] Debug service listening on ws://127.0.0.1:46215/Gf2rsDmiuAU=/ws
[        ] 💪 Running with sound null safety 💪
[   +1 ms] 🔥  To hot restart changes while running, press "r" or "R".
[        ] For a more detailed help message, press "h". To quit, press "q".
[ +877 ms] Child(dirty, dependencies: [Parent<String>], state: _ChildState#02754(lifecycle state: initialized))
[   +6 ms] didChangeDependencies works!
[+4513 ms] Child(dependencies: [Parent<String>], state: _ChildState#02754)
[ +432 ms] ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
[        ] The following assertion was thrown while finalizing the widget tree:
[        ] Looking up a deactivated widget's ancestor is unsafe.
[        ] At this point the state of the widget's element tree is no longer stable.
[        ] To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by
[        ] calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
[        ] When the exception was thrown, this was the stack:
[        ] dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 236:49  throw_
[        ] packages/flutter/src/widgets/framework.dart 3944:9                            <fn>
[        ] packages/flutter/src/widgets/framework.dart 3957:14                           [_debugCheckStateIsActiveForAncestorLookup]
[        ] packages/flutter/src/widgets/framework.dart 3973:12                           dependOnInheritedWidgetOfExactType
[        ] packages/test/main.dart 47:19                                                 of
[        ] packages/test/main.dart 78:26                                                 dispose
[        ] packages/flutter/src/widgets/framework.dart 4800:11                           unmount
[        ] packages/flutter/src/widgets/framework.dart 1847:12                           [_unmount]
[        ] dart-sdk/lib/internal/iterable.dart 39:13                                     forEach
[        ] packages/flutter/src/widgets/framework.dart 1856:15                           [_unmountAll]
[        ] packages/flutter/src/widgets/framework.dart 2840:27                           <fn>
[        ] packages/flutter/src/widgets/framework.dart 2473:15                           lockState
[        ] packages/flutter/src/widgets/framework.dart 2839:7                            finalizeTree
[        ] packages/flutter/src/widgets/binding.dart 877:7                               drawFrame
[        ] packages/flutter/src/rendering/binding.dart 328:5                             [_handlePersistentFrameCallback]
[        ] packages/flutter/src/scheduler/binding.dart 1144:15                           [_invokeFrameCallback]
[        ] packages/flutter/src/scheduler/binding.dart 1082:9                            handleDrawFrame
[        ] packages/flutter/src/scheduler/binding.dart 998:5                             [_handleDrawFrame]
[        ] lib/_engine/engine/platform_dispatcher.dart 963:13                            invoke
[        ] lib/_engine/engine/platform_dispatcher.dart 152:5                             invokeOnDrawFrame
[        ] lib/_engine/engine.dart 262:45                                                <fn>
[        ] ════════════════════════════════════════════════════════════════════════════════════════════════════


```

<!--
     Run `flutter analyze` and attach any output of that command below.
     If there are any analysis errors, try resolving them before filing this issue.
-->

```
Analyzing test...                                                       
No issues found! (ran in 0.9s)
```

<!-- Finally, paste the output of running `flutter doctor -v` here. -->

```
[✓] Flutter (Channel stable, 2.2.1, on Linux, locale en_US.UTF-8)
    • Flutter version 2.2.1 at /home/dh/development/flutter
    • Framework revision 02c026b03c (9 days ago), 2021-05-27 12:24:44 -0700
    • Engine revision 0fdb562ac8
    • Dart version 2.13.1

[✗] Android toolchain - develop for Android devices
    ✗ Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).
      If the Android SDK has been installed to a custom location, please use
      `flutter config --android-sdk` to update to that location.


[✓] Chrome - develop for the web
    • Chrome at google-chrome

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).

[✓] VS Code (version 1.56.2)
    • VS Code at /usr/share/code
    • Flutter extension version 3.23.0

[✓] Connected device (1 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 91.0.4472.77

! Doctor found issues in 2 categories.
```

</details>