Is it possible to listen for changes, and upon a change, get those new values from a separate class and update variable in current class?

Viewed 7123

So, I am in my home_screen dart file and I have a Text in it where I want it to display the live value from another class's properties value. When I update the class's properties value from another script I want my home_screen Text to update to that new value. My class in a separate file is the following (simplified) :

class MyClass {

  static int myNumber = 10;

}

I want the following Text to update with the value of myNumber in another file:

Text('iWantThisToDisplayLiveMyNumber'),

When I change the value of myNumber from yet another random script how do I get the Text to update in live time to always be myNumber?

2 Answers

Look into Providers.

class MyClass with ChangeNotifier {
        
   static int myNumber = 10;
    
   void changeNumber(){
       myNumber = 1;
       notifyListeners();
   }

 }

In your Widget class you can set up a "listener" like this:

int updatedNumber = Provider.of<MyClass>(context, listen: true).myNumber;

This is a basic and bad way of doing this. Please check out the "ChangeNotifier" "ChangeNotifierProvider" and "Provider.of" Sections in the docs here.

https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple

Its pretty easy to get started with. Good luck

You can make use of the getter and setter functions.

In the example below we are printing happy birthday when the person's age changes:

class Person {
  int _age;

  Person(this._age);

  int get age => _age;
  
  set age(int newValue) {
    print("Happy birthday! You have a new Age.");
    //do some awsome things here when the age changes
    _age = newValue;
  }
}

The usage is exactly as you are used to:

final newPerson = Person(20);
  
print(newPerson.age); //20
newPerson.age = 21; //prints happy birthday
print(newPerson.age); //21
Related