Flutter: Update widget using Provider with nested class

Issue

I am using Provider and I am trying to have my widgets updated once a method is called under a nested object of the ChangeNotifierProvider (calling updateColor() in Seat which is nested in Aircraft).

As mentioned in Flutter Provider Nested Objects question, I tried using ChangeNotifierProxyProvider but without success.

How can I ensure my widgets are updated when I call updateColor()?

Code example:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

main() {
  runApp(MultiProvider(providers: [
    ChangeNotifierProvider<Aircraft>(create: (_) => Aircraft()),
  ], child: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Consumer<Aircraft>(builder: (context, aircraft, _) {
            return Column(
              children: <Widget>[
                Text('${aircraft.aircraftManufacturer.toString()}'),
                Text('${aircraft.emptyWeight}'),
                Text('${aircraft.length}'),
                Column(
                    children: aircraft.seats.entries.map((seat) {
                  return Text(
                      'Row ${seat.key} is Class: ${seat.value.seatClass.toString()}, '
                      + 'emergencyExitSeat: ${seat.value.emergencyExitSeat.toString()}, '
                      + ' emergencyExitSeat: ${seat.value.seatColor.toString()},');
                }).toList()),
                Column(
                    children: aircraft.seats.entries.map((seat) {
                  return RaisedButton(
                    onPressed: () => seat.value.updateColor(),
                    child: Text('Change color for ${seat.key}'),
                  );
                }).toList())
              ],
            );
          }),
        ),
      ),
    );
  }
}

enum Manufacturer { Airbus, Boeing, Embraer }
enum SeatClass { First, Business, Economy }

class Aircraft extends ChangeNotifier {
  Manufacturer _aircraftManufacturer;
  double _emptyWeight;
  double _length;
  Map<int, Seat> _seats;

  Manufacturer get aircraftManufacturer => _aircraftManufacturer;
  double get emptyWeight => _emptyWeight;
  double get length => _length;
  Map<int, Seat> get seats => _seats;

  Aircraft() {
    _aircraftManufacturer = Manufacturer.Airbus;
    _emptyWeight = 190.0;
    _length = 66.80;
    _seats = new Map<int, Seat>();
    _seats.putIfAbsent(
        1, () => new Seat(SeatClass.First, false, Color(0xFF42A5F5)));
    _seats.putIfAbsent(
        2, () => new Seat(SeatClass.Business, false, Color(0xFF42A4F5)));
    _seats.putIfAbsent(
        3, () => new Seat(SeatClass.Economy, false, Color(0xFF42A3F5)));
    _seats.putIfAbsent(
        4, () => new Seat(SeatClass.Economy, true, Color(0xFF42A2F5)));
  }
}

class Seat extends ChangeNotifier {
  SeatClass _seatClass;
  bool _emergencyExitSeat;
  Color _seatColor;

  Seat(SeatClass seatClass, bool emergencyExitSeat, Color seatColor) {
    _seatClass = seatClass;
    _emergencyExitSeat = emergencyExitSeat;
    _seatColor = seatColor;
  }

  SeatClass get seatClass => _seatClass;
  bool get emergencyExitSeat => _emergencyExitSeat;
  Color get seatColor => _seatColor;

  void updateColor() {
    _seatColor = Color(0xFF9EB26E);
    print('Color updated');
    notifyListeners();
  }
}

Solution

Why are you making seat also a ChangeNotifier, it doesn’t need to notifyListeners directly since it is nested and created inside Aircraft, so you need to only make Aircraft a ChangeNotifier and provide a method inside Seat to change color (a setter is enough) :

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

main() {
  runApp(MultiProvider(providers: [
    ChangeNotifierProvider<Aircraft>(create: (_) => Aircraft()),
  ], child: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Consumer<Aircraft>(builder: (context, aircraft, _) {
            return Column(
              children: <Widget>[
                Text('${aircraft.aircraftManufacturer.toString()}'),
                Text('${aircraft.emptyWeight}'),
                Text('${aircraft.length}'),
                Column(
                    children: aircraft.seats.entries.map((seat) {
                      return Text(
                          'Row ${seat.key} is Class: ${seat.value.seatClass.toString()}, '
                              + 'emergencyExitSeat: ${seat.value.emergencyExitSeat.toString()}, '
                              + ' emergencyExitSeat: ${seat.value.seatColor.toString()},');
                    }).toList()),
                Column(
                    children: aircraft.seats.entries.map((seat) {
                      return RaisedButton(
                        onPressed: () => aircraft.onSeatColorUpdate(seat.value),
                        child: Text('Change color for ${seat.key}'),
                      );
                    }).toList())
              ],
            );
          }),
        ),
      ),
    );
  }
}

enum Manufacturer { Airbus, Boeing, Embraer }
enum SeatClass { First, Business, Economy }

class Aircraft extends ChangeNotifier {
  Manufacturer _aircraftManufacturer;
  double _emptyWeight;
  double _length;
  Map<int, Seat> _seats;

  Manufacturer get aircraftManufacturer => _aircraftManufacturer;
  double get emptyWeight => _emptyWeight;
  double get length => _length;
  Map<int, Seat> get seats => _seats;

  Aircraft() {
    _aircraftManufacturer = Manufacturer.Airbus;
    _emptyWeight = 190.0;
    _length = 66.80;
    _seats = new Map<int, Seat>();
    _seats.putIfAbsent(
        1, () => new Seat(SeatClass.First, false, Color(0xFF42A5F5)));
    _seats.putIfAbsent(
        2, () => new Seat(SeatClass.Business, false, Color(0xFF42A4F5)));
    _seats.putIfAbsent(
        3, () => new Seat(SeatClass.Economy, false, Color(0xFF42A3F5)));
    _seats.putIfAbsent(
        4, () => new Seat(SeatClass.Economy, true, Color(0xFF42A2F5)));
  }
  void onSeatColorUpdate(Seat seat){//you should edit this method to accept color as parameter
    seat.updateColor();//you should edit this method to accept color as parameter
    notifyListeners();
  }
}

class Seat {
  SeatClass _seatClass;
  bool _emergencyExitSeat;
  Color _seatColor;

  Seat(SeatClass seatClass, bool emergencyExitSeat, Color seatColor) {
    _seatClass = seatClass;
    _emergencyExitSeat = emergencyExitSeat;
    _seatColor = seatColor;
  }

  SeatClass get seatClass => _seatClass;
  bool get emergencyExitSeat => _emergencyExitSeat;
  Color get seatColor => _seatColor;

  void updateColor() {
    _seatColor = Color(0xFF9EB26E);
    print('updateColor in class seat');
  }
}

Answered By – Haidar

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.