Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getElementForInheritedWidgetOfExactType return null while reordering item with ReordableListView #88570

Open
woprandi opened this issue Aug 20, 2021 · 8 comments
Labels
f: material design flutter/packages/flutter/material repository. f: scrolling Viewports, list views, slivers, etc. found in release: 2.2 Found to occur in 2.2 found in release: 2.5 Found to occur in 2.5 framework flutter/packages/flutter repository. See also f: labels. has reproducible steps The issue has been confirmed reproducible and is ready to work on P2 Important issues not at the top of the work list team-design Owned by Design Languages team triaged-design Triaged by Design Languages team

Comments

@woprandi
Copy link
Contributor

woprandi commented Aug 20, 2021

Steps to Reproduce

See this example

minimal code sample
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _data = ["a", "b", "c", "d"];

  @override
  Widget build(BuildContext context) {
    return Provider<String>(
      create: (_) => "Foo",
      child: Scaffold(
        body: ReorderableListView(
          children: _data.map((v) {
            return ListItem(
              key: ValueKey(v),
              value: v,
            );
          }).toList(),
          onReorder: (oldIndex, newIndex) {
            if (oldIndex < newIndex) {
              newIndex--;
            }

            setState(() {
              _data.insert(newIndex, _data.removeAt(oldIndex));
            });
          },
        ),
      ),
    );
  }
}

class ListItem extends StatelessWidget {
  final String value;

  const ListItem({Key? key, required this.value}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final s = context.watch<String>();
    print(s);

    return ListTile(title: Text('$value $s'));
  }
}

Each list item widget get the exposed String to build with context.watch method (getElementForInheritedWidgetOfExactType is called under the hood).
On all current channels (tested on current stable and master) getElementForInheritedWidgetOfExactType now returns null during reorder and throw a ProviderNotFoundException.
It works on flutter 2.0.6

Expected results: getElementForInheritedWidgetOfExactType return the exposed value during reorder

Actual results: getElementForInheritedWidgetOfExactType return null during reorder (regression)

Logs
flutter run -d chrome --verbose
[  +78 ms] executing: uname -m
[  +36 ms] Exit code 0 from: uname -m
[        ] x86_64
[   +7 ms] executing: [/home/william/Documents/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
[        ] f4abaa0735eba4dfd8f33f73363911d63931fe03
[        ] executing: [/home/william/Documents/flutter/] git tag --points-at f4abaa0735eba4dfd8f33f73363911d63931fe03
[  +17 ms] Exit code 0 from: git tag --points-at f4abaa0735eba4dfd8f33f73363911d63931fe03
[        ] 2.2.3
[   +6 ms] executing: [/home/william/Documents/flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[   +5 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/stable
[        ] executing: [/home/william/Documents/flutter/] git ls-remote --get-url origin
[   +5 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[  +99 ms] executing: [/home/william/Documents/flutter/] git rev-parse --abbrev-ref HEAD
[   +6 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] stable
[  +64 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.
[   +2 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.
[  +63 ms] executing: /home/william/Android/Sdk/platform-tools/adb devices -l
[  +19 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.
[   +2 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.
[  +83 ms] executing: /home/william/Android/Sdk/platform-tools/adb devices -l
[  +13 ms] Skipping pub get: version match.
[ +100 ms] Found plugin integration_test at /home/william/Documents/flutter/packages/integration_test/
[ +236 ms] Found plugin integration_test at /home/william/Documents/flutter/packages/integration_test/
[   +8 ms] Generating /home/william/Documents/repos/flutter_playground/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
[ +121 ms] List of devices attached
[   +3 ms] List of devices attached
[  +81 ms] Launching lib/main.dart on Chrome in debug mode...
[ +124 ms] Updating assets
[ +112 ms] Waiting for connection from debug service on Chrome...
[  +37 ms] Found plugin integration_test at /home/william/Documents/flutter/packages/integration_test/
[  +36 ms] Found plugin integration_test at /home/william/Documents/flutter/packages/integration_test/
[  +81 ms] <- reset
[   +6 ms] /home/william/Documents/flutter/bin/cache/dart-sdk/bin/dart --disable-dart-dev /home/william/Documents/flutter/bin/cache/artifacts/engine/linux-x64/frontend_server.dart.snapshot --sdk-root
/home/william/Documents/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.CUQVAV/flutter_tool.JCISQY/app.dill --libraries-spec file:///home/william/Documents/flutter/bin/cache/flutter_web_sdk/libraries.json --packages
/home/william/Documents/repos/flutter_playground/.dart_tool/package_config.json -Ddart.vm.profile=false -Ddart.vm.product=false --enable-asserts --track-widget-creation --filesystem-root /tmp/flutter_tools.CUQVAV/flutter_tools.DUUEPT
--filesystem-scheme org-dartlang-app --initialize-from-dill build/b1b715402d823b7fd5c2b68d2edcb2ce.cache.dill.track.dill --platform file:///home/william/Documents/flutter/bin/cache/flutter_web_sdk/kernel/flutter_ddc_sdk_sound.dill
--sound-null-safety
[  +16 ms] <- compile org-dartlang-app:/web_entrypoint.dart
[+24121 ms] Waiting for connection from debug service on Chrome... (completed in 24,3s)
[   +1 ms] Synced 28.5MB.
[   +1 ms] <- accept
[        ] Caching compiled dill
[ +151 ms] Using Google Chrome 92.0.4515.131 

[ +431 ms] [CHROME]:
[        ] [CHROME]:DevTools listening on ws://127.0.0.1:38999/devtools/browser/8fb0be36-470a-4c7e-9171-a3008335d38c
[ +470 ms] DwdsInjector: Received request for entrypoint at http://localhost:43839/main_module.bootstrap.js
[  +19 ms] MetadataProvider: Loading debug metadata...
[  +29 ms] MetadataProvider: Loaded debug metadata (sound null safety)
[  +18 ms] DwdsInjector: Injected debugging metadata for entrypoint at http://localhost:43839/main_module.bootstrap.js
[+2469 ms] ChromeProxyService: Initializing expression compiler for main_module.bootstrap.js with sound null safety: true
[  +90 ms] DevHandler: Debug service listening on ws://127.0.0.1:40677/E0TG9sRMVw4=/ws

[  +33 ms] This app is linked to the debug service: ws://127.0.0.1:40677/E0TG9sRMVw4=/ws
[   +9 ms] Debug service listening on ws://127.0.0.1:40677/E0TG9sRMVw4=/ws
[        ] 💪 Running with sound null safety 💪
[   +3 ms] 🔥  To hot restart changes while running, press "r" or "R".
[        ] For a more detailed help message, press "h". To quit, press "q".
[+2502 ms] Foo
[ +153 ms] Foo
[  +48 ms] Foo
[  +40 ms] Foo
[+3435 ms] ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
[        ] The following ProviderNotFoundException was thrown building ListItem-[<'a'>](dirty):
[        ] Error: Could not find the correct Provider<String> above this ListItem Widget
[        ] This happens because you used a `BuildContext` that does not include the provider
[        ] of your choice. There are a few common scenarios:
[        ] - You added a new provider in your `main.dart` and performed a hot-reload.
[        ]   To fix, perform a hot-restart.
[        ] - The provider you are trying to read is in a different route.
[        ]   Providers are "scoped". So if you insert of provider inside a route, then
[        ]   other routes will not be able to access that provider.
[        ] - You used a `BuildContext` that is an ancestor of the provider you are trying to read.
[        ]   Make sure that ListItem is under your MultiProvider/Provider<String>.
[        ]   This usually happens when you are creating a provider and trying to read it immediately.
[        ]   For example, instead of:
[        ]   ```
[        ]   Widget build(BuildContext context) {
[        ]     return Provider<Example>(
[        ]       create: (_) => Example(),
[        ]       // Will throw a ProviderNotFoundError, because `context` is associated
[        ]       // to the widget that is the parent of `Provider<Example>`
[        ]       child: Text(context.watch<Example>()),
[        ]     ),
[        ]   }
[        ]   ```
[        ]   consider using `builder` like so:
[        ]   ```
[        ]   Widget build(BuildContext context) {
[        ]     return Provider<Example>(
[        ]       create: (_) => Example(),
[        ]       // we use `builder` to obtain a new `BuildContext` that has access to the provider
[        ]       builder: (context) {
[        ]         // No longer throws
[        ]         return Text(context.watch<Example>()),
[        ]       }
[        ]     ),
[        ]   }
[        ]   ```
[   +2 ms] If none of these solutions work, consider asking for help on StackOverflow:
[        ] https://stackoverflow.com/questions/tagged/flutter
[        ] The relevant error-causing widget was:
[        ]   ListItem-[<'a'>] file:///home/william/Documents/repos/flutter_playground/lib/main.dart:31:20
[        ] 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/provider/src/provider.dart 358:7                                     _inheritedElementOf
[        ] packages/provider/src/provider.dart 295:30                                    of
[        ] packages/provider/src/provider.dart 702:21                                    WatchContext.watch
[        ] packages/flutter_playground/main.dart 58:23                                   build
[        ] packages/flutter/src/widgets/framework.dart 4648:28                           build
[        ] packages/flutter/src/widgets/framework.dart 4574:15                           performRebuild
[        ] packages/flutter/src/widgets/framework.dart 4267:5                            rebuild
[        ] packages/flutter/src/widgets/framework.dart 2582:31                           buildScope
[        ] packages/flutter/src/widgets/binding.dart 875:9                               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>
[        ] ════════════════════════════════════════════════════════════════════════════════════════════════════
[+1917 ms] Foo
[   +9 ms] Foo
[  +14 ms] Foo
[   +8 ms] Foo


flutter analyze         
Analyzing flutter_playground...                                         
No issues found! (ran in 1.9s)
flutter doctor -v
[✓] Flutter (Channel stable, 2.2.3, on Linux, locale fr_FR.UTF-8)
    • Flutter version 2.2.3 at /home/william/Documents/flutter
    • Framework revision f4abaa0735 (il y a 7 semaines), 2021-07-01 12:46:11 -0700
    • Engine revision 241c87ad80
    • Dart version 2.13.4

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /home/william/Android/Sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /home/william/.local/share/JetBrains/Toolbox/apps/AndroidStudio/ch-0/203.7621141/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/linux#android-setup for more details.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 12.0.1 (Fedora 12.0.1-1.fc34)
    • cmake version 3.20.5
    • ninja version 1.10.2
    • pkg-config version 1.7.3

[✓] Android Studio (version 2020.3)
    • Android Studio at /home/william/.local/share/JetBrains/Toolbox/apps/AndroidStudio/ch-0/203.7621141
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[✓] IntelliJ IDEA Community Edition (version 2021.2)
    • IntelliJ at /home/william/.local/share/JetBrains/Toolbox/apps/IDEA-C/ch-0/212.4746.92
    • Flutter plugin version 59.0.4
    • Dart plugin version 212.4746.57

[✓] VS Code (version 1.59.0)
    • VS Code at /usr/share/code
    • Flutter extension version 3.22.0

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Linux
    • Chrome (web)    • chrome • web-javascript • Google Chrome 92.0.4515.131

! Doctor found issues in 1 category.

@woprandi
Copy link
Contributor Author

After bisecting,the regression come from 994133c

@TahaTesser TahaTesser added the in triage Presently being triaged by the triage team label Aug 23, 2021
@TahaTesser
Copy link
Member

HI @woprandi
Thanks for filing the issue, I can confirm on multiple channels

stable master
❗️ ❗️

Check flutter doctor -v outputs for each channel below

flutter doctor -v
[✓] Flutter (Channel stable, 2.2.3, on Linux, locale en_US.UTF-8)
    • Flutter version 2.2.3 at /home/taha/Code/flutter_stable
    • Framework revision f4abaa0735 (8 weeks ago), 2021-07-01 12:46:11 -0700
    • Engine revision 241c87ad80
    • Dart version 2.13.4

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /home/taha/Code/android-sdk
    • Platform android-30, build-tools 30.0.3
    • ANDROID_SDK_ROOT = /home/taha/Code/android-sdk
    • Java binary at: /home/taha/Code/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • Ubuntu clang version 12.0.0-3ubuntu1~21.04.1
    • cmake version 3.18.4
    • ninja version 1.10.1
    • pkg-config version 0.29.2

[✓] Android Studio (version 2020.3)
    • Android Studio at /home/taha/Code/android-studio
    • Flutter plugin version 58.0.2
    • Dart plugin version 203.8292
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[✓] VS Code (version 1.59.1)
    • VS Code at /usr/share/code
    • Flutter extension version 3.25.0

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Linux
    • Chrome (web)    • chrome • web-javascript • Google Chrome 92.0.4515.159

• No issues found!
[✓] Flutter (Channel master, 2.5.0-7.0.pre.187, on Pop!_OS 21.04 5.11.0-7620-generic, locale en_US.UTF-8)
    • Flutter version 2.5.0-7.0.pre.187 at /home/taha/Code/flutter_master
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 05bfbbfbec (9 hours ago), 2021-08-22 21:37:03 -0400
    • Engine revision 710af46d53
    • Dart version 2.15.0 (build 2.15.0-42.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /home/taha/Code/android-sdk
    • Platform android-30, build-tools 30.0.3
    • ANDROID_SDK_ROOT = /home/taha/Code/android-sdk
    • Java binary at: /home/taha/Code/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • Ubuntu clang version 12.0.0-3ubuntu1~21.04.1
    • cmake version 3.18.4
    • ninja version 1.10.1
    • pkg-config version 0.29.2

[✓] Android Studio (version 2020.3)
    • Android Studio at /home/taha/Code/android-studio
    • Flutter plugin version 58.0.2
    • Dart plugin version 203.8292
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[✓] VS Code (version 1.59.1)
    • VS Code at /usr/share/code
    • Flutter extension version 3.25.0

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Pop!_OS 21.04 5.11.0-7620-generic
    • Chrome (web)    • chrome • web-javascript • Google Chrome 92.0.4515.159

• No issues found!

✅: No Issue ❗️: Issue reproduced

@TahaTesser TahaTesser added f: material design flutter/packages/flutter/material repository. f: scrolling Viewports, list views, slivers, etc. found in release: 2.2 Found to occur in 2.2 found in release: 2.5 Found to occur in 2.5 framework flutter/packages/flutter repository. See also f: labels. has reproducible steps The issue has been confirmed reproducible and is ready to work on and removed in triage Presently being triaged by the triage team labels Aug 23, 2021
@HansMuller
Copy link
Contributor

CC @darrenaustin

@darrenaustin darrenaustin self-assigned this Aug 27, 2021
@woprandi
Copy link
Contributor Author

Any news ?

@Kp0c
Copy link

Kp0c commented Oct 14, 2021

It is still reproducible on the master branch.
Any ideas for workarounds?

@woprandi
Copy link
Contributor Author

@Kp0c You can wrap your List by an Overlay. Check the regression commit 994133c

@alexeyinkin
Copy link

Can we have a priority label on this? If not milestone.

@darrenaustin
Copy link
Contributor

Sorry we haven't had a chance to address this yet. The core problem is that as of 994133c, the reorderable list no longer uses its own Overlay to display the dragged item. It reuses the surrounding overlay (usually the one provided by MaterialApp) so that the items can be seen outside of the list itself when dragging.

So in this case while the ListItem is being dragged, it is reparented to the MaterialApp's overlay which doesn't see the Provider widget wrapping the list, hence the crash.

Not sure the best way to address this in the framework yet, but for now if you need a workaround you can try one of these options:

  • Move the Provider higher than the MaterialApp in the widget tree:
      return Provider<String>(
        create: (_) => "Foo",
        child: MaterialApp(home: HomePage())
      );
  • Wrap the ReorderableListView in its own Overlay:
        child: Scaffold(
          body: Overlay(initialEntries: [
              OverlayEntry(
                builder: (context) {
                  return ReorderableListView(
                    children: _data.map((v) {
                      return ListItem(
                        key: ValueKey(v),
                        value: v,
                      );
                    }).toList(),
                    onReorder: (oldIndex, newIndex) {
                      if (oldIndex < newIndex) {
                        newIndex--;
                      }
    
                      setState(() {
                        _data.insert(newIndex, _data.removeAt(oldIndex));
                      });
                    },
                  );
                },
              )
            ],
          ),
        ),

@Piinks Piinks added the P2 Important issues not at the top of the work list label Mar 17, 2023
@flutter-triage-bot flutter-triage-bot bot added multiteam-retriage-candidate team-design Owned by Design Languages team triaged-design Triaged by Design Languages team labels Jul 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
f: material design flutter/packages/flutter/material repository. f: scrolling Viewports, list views, slivers, etc. found in release: 2.2 Found to occur in 2.2 found in release: 2.5 Found to occur in 2.5 framework flutter/packages/flutter repository. See also f: labels. has reproducible steps The issue has been confirmed reproducible and is ready to work on P2 Important issues not at the top of the work list team-design Owned by Design Languages team triaged-design Triaged by Design Languages team
Projects
None yet
Development

No branches or pull requests

8 participants