phil magnuson
phil magnuson

Reputation: 71

flutter dependOnInheritedWidgetOfExactType fails in test

App runs correctly with flutter run

With flutter drive --target=test_driver/main.dart the call to dependOnInheritedWidgetOfExactType returns null

Some relevant code:

class TimerServiceProvider extends InheritedWidget {
  const TimerServiceProvider({Key key, this.service, Widget child})
      : super(key: key, child: child);
  final TimerService service;
  @override
  bool updateShouldNotify(TimerServiceProvider old) => service != old.service;
}

in MyApp the widget tree starts with TimerServiceProvider

final timerService = TimerService();

  @override
  Widget build(BuildContext context) {
    return TimerServiceProvider(
        // provide timer service to all widgets of your app
        service: timerService,
...

on one of the pages

timerService = TimerService.of(context);

In the function TimerService.of, dependOnInheritedWidgetOfExactType returns null. This works fine during the normal app execution and returns null if run from flutter driver.

static TimerService of(BuildContext context) {
    var provider =
        context.dependOnInheritedWidgetOfExactType<TimerServiceProvider>();
    return provider.service;
  }

flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.17.5, on Mac OS X 10.15.5 19F101, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.1)
[✓] Xcode - develop for iOS and macOS (Xcode 11.6)
[✓] Android Studio (version 3.5)
[✓] VS Code (version 1.47.2)
[✓] Connected device (1 available)

• No issues found!

Upvotes: 1

Views: 770

Answers (1)

Heitor
Heitor

Reputation: 612

Phil, try to set a type for your service.

TimerService timerService = TimerService(); //HERE

  @override
  Widget build(BuildContext context) {
    return TimerServiceProvider(
        // provide timer service to all widgets of your app
        service: timerService,

I faced a similar error with my tests, my InheritedWidget has a generic type. My app runs as supposed to, but the tests fail at the same point as yours.

Upvotes: 2

Related Questions