0

I'm trying to setup a InheritedWidget in flutter allowing a model to be accessed from anywhere in the application.

It works great until I try to split my application into multiple files. It seems that calling context.inheritFromWidgetOfExactType(...) only workes if the called from the same file as where the InheritedWidget is inserted into the tree. Simply by moving a block of code from one file to another results in null being returned from that method.

The code is as follows:

The basic app is setup from the demo app import 'package:flutter/material.dart'; import 'views/home.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new StateContainer(
      model: new AppState(),
      child: new MaterialApp(
        title: 'Flutter Demo',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new HomePage(),
      ),
    );
  }
}

The InheritedWidget is defined with a model as follows:

class StateContainer extends InheritedWidget {
  final AppState model;

  StateContainer({Key key, this.model, Widget child})
      : super(key: key, child: child);

  @override
  bool updateShouldNotify(StateContainer old) {
    return false;
  }

  static AppState of(BuildContext context) {
    return (context.inheritFromWidgetOfExactType(StateContainer)
            as StateContainer).model;
  }
}

class AppState {
  final String test = "Hi";
}

Finally, the HomePage is defined by:

import 'package:flutter/material.dart';
import 'package:ftest/main.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var model = StateContainer.of(context);
    return Container(
      child: Center(
        child: Text(model.test),
      ),
    );
  }
}

With this last block in the same file as the other two, the app works as expected. By simply moving it into a new file however, the error message The getter 'model' was called on null. is thrown.

I can only guess that somewhere the BuildContext isn't being passed properly, but nothing I've tried as fixed it. Any ideas?

Jon
  • 401
  • 3
  • 11

0 Answers0