简体   繁体   中英

Flutter using inherited widgets with Navigator returning NoSuchMethodError

I'm making a flutter app. I have a homepage widget which shows two things - device code; temperature At first, these are set to some default values, but the user then goes from the home page to a new route, call this widget the sensor widget. In this new page, it basically connects to a sensor. This sensor sends out the device code and temperature, and I am able to show it inthe sensor widget.

The problem comes when i want to show this new information onthe homepage. I made a button where the user can go back to the homepage, but I want a way to update the homepage with the values I have in my sensor widget.

Im making use of the InheritedWidget class to make this happen, but I keep getting a null error when I try to access the variables in the homepage.

Below is the inherited widget class for this.

class TemperatureContext extends InheritedWidget {
    final int _deviceCode;
    final double _temperature;

    int    get deviceCode => _deviceCode;
    double get temperature => _temperature;

    set deviceCode(int d) {_deviceCode = d;}
    set temperature(double t) {_temperature = t}

    TemperatureContext(this.deviceCode, this.temperature, {Key key, Widget child})
    .super(key: key, child:child)

    @override
    bool updateShouldNotify(Widget oldWidget) {
        return (temperature != oldWidget.temperature && deviceCode != oldWidget.deviceCode) }

    static TemperatureContext of(BuildContext context) {
        return context.inheritFromWidgetOfExactType(TemperatureContext) }
    }

I then have the homepage, new_widget is a function that builds a widget based on the

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

    class _HomePageState extends State<HomePage> {

        static int deviceCode = 0;
        static double deviceCode = get_temp_globally();


        @override
        Widget build(BuildContext context) {
        final tempContext = TemperatureContext.of(context);
        Widget output = new MaterialApp(
            home: new Scaffold(
                appBar: new AppBar(
                title: new Text('Homepage'),
            ),
            body: new Column(
              children: <Widget>[
                new_widget(tempContext.deviceCode, tempContext.temperature),
                new FlatButton(
                    child: new Text('Set new sensor'),
                    onPressed: () {
                      Navigator.of(context).pushNamed('/ChangePage');
                    })
              ],
            )));
    return output;
  }

Next is the change page widget where the user is taken to when they press the button in the home page

class SensorWidget extends StatefulWidget {
  SensorWidget({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _SensorWidgetState createState() => new _SensorWidgetState();

}

class _SensorWidgetState extends State<SensorWidget> {
  static int deviceCode  = 0;
  static double temperature  = get_temp_globally();

  /* Some code that gets the deviceCode,
  temperature and sets them to the above
  variables */

  @override
  Widget build(BuildContext context) {
    output = TemperatureContext(
      deviceCode,
      temperature,
      child: MaterialApp(
        home: new Scaffold(
          appBar: new AppBar(
            title: const Text('Sensor widget'),
            actions: _buildActionButtons(),
          ),
          floatingActionButton: _buildScanningButton(),
          body: new Container(
            child: new FlatButton(
              child: new Text("Go back"),
              onPressed: () {
              Navigator.of(context).pop(true);
              }
            ),
          ),

        ),
        ),
      );
      return output;
  }
}

And this is my main.dart file

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

}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Temperature detector',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new HomePage(),
      routes: <String, WidgetBuilder> {
        '/HomePage' : (BuildContext context) => new HomePage(),
        '/SensorWidget': (BuildContext context) => new SensorWidget(),
      },
    );
  }
}

Basically when I put the new_widget function in my HomePage class (which I didnt put here, but basically builds a widget based on the two arguements provided), I get a "NoSuchMethodError": the getter deviceCode was called on null.

I dont get why this is null since I already initialized it. Any help? Thanks

See https://flutter.io/flutter-for-android/#what-is-the-equivalent-of-startactivityforresult :

The Navigator class handles routing in Flutter and is used to get a result back from a route that you have pushed on the stack. This is done by awaiting on the Future returned by push().

For example, to start a location route that lets the user select their location, you could do the following:

Map coordinates = await Navigator.of(context).pushNamed('/location');

And then, inside your location route, once the user has selected their location you can pop the stack with the result:

Navigator.of(context).pop({"lat":43.821757,"long":-79.226392});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM