Getting a changed value within the same class?

Issue

I’m trying to access a boolean that gets set outside of the class. When I check the value in the getter, it is correct. But, when I try to access that value from a different method within the same class, I’m getting the old unchanged value.

Is there a way around this or would I need two separate classes to do this? Here’s a little snippet of code.

class RoutineProvider with ChangeNotifier {
  bool _isNight = false;

  set isNight(bool newValue) {
    print(newValue); // returns true
    _isNight = newValue;
    print(_isNight); // returns true
    notifyListeners();
  }

  bool get isNight => _isNight;

  Future<Routine> basicRoutine() {
    print(RoutineProvider().isNight); // returns false
    if (RoutineProvider().isNight) {
      return firestore
          .collection('routines')
          .doc('basic_routine_night')
          .get()
          .then((snap) => Routine.fromDocSnap(snap));
    }

    return firestore
        .collection('routines')
        .doc('basic_routine')
        .get()
        .then((snap) => Routine.fromDocSnap(snap));
  }
}

Solution

Calling RoutineProvider() seems like it would instantiate a new RoutineProvider object each time. You could try changing bool _isNight = false to static bool _isNight = false

Answered By – Zac

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *