Is Dart/Flutter has a listener function?

Viewed 315

The listener function can listen to any parameter type(not only listener type). This has nothing related to widgets.

ex.

int a = 0;
listener((a>0)=>print("A = $a"));
a= 1; //A = 1
a= -1; //
a= 2; //A = 2
2 Answers

You can use ValueNotifier for this. It's a ChangeNotifier that is triggered when the value is replaced with something that is not equal to the old value as evaluated by the equality operator ==.

Here is a nice tutorial about this approach.

The basic method is to create the function for updating the parameter that you want to add to the listener.

void test() {
  int a = 0;
  void updateA(newA) {
    if(newA is! int) return;
    a = newA;
    if (a > 0) print("A = $a");
  }
  updateA(1);
  updateA(-1);
  updateA(2);
}

A better way is to create parameters with class.

void main() {
  ParameterWithListener a = ParameterWithListener(data: 0);
  a.listener = () {
    if (a.data is int && a.data > 0) print("A = ${a.data}");
  };
  a.update(1);
  a.update(-1);
  a.update(2);
}

class ParameterWithListener {
  ParameterWithListener({this.data, this.listener});

  dynamic data;
  Function()? listener;

  Future update(data) async {
    this.data = data;
    if (listener is Function()) await listener!();
  }
}

result:

A = 1
A = 2
Related