1

I know there are ValueNotifier, ChangeNotifier and of course Stream, but I can't find any class that can provide the new value directly to the listeners. I could of course create my own, but I'm wondering if there is such a class "built in" to Flutter?

Example (DirectValueNotifier is what I'm looking for):

class MyClass extends DirectValueNotifier<String>{
    void doSomething(){
        String s = DateTime.now().toIso8601String();
        notifyListeners(s);
    }
}



MyClass myObj = MyClass();
myObj.addListener((s){
    print('The time is $s');
});

Magnus
  • 17,157
  • 19
  • 104
  • 189

1 Answers1

0

There isn't a built-in class specifically called DirectValueNotifier that provides the new value directly to the listeners as far as I know.

However, you can achieve similar functionality by extending the ValueNotifier class and adding a custom method to notify the listeners with a new value.

import 'package:flutter/foundation.dart';

void main() {
  MyClass myObj = MyClass('Initial Value');

  myObj.addListener(() {
    print('Listener value: ${myObj.value}');
  });

  myObj.doSomething();
}

class MyClass extends ValueNotifier<String> {
  MyClass(String value) : super(value);

  void notifyListenersWithValue(String value) {
    this.value = value;

    notifyListeners();
  }

  void doSomething() {
    final String s = DateTime.now().toIso8601String();
    notifyListenersWithValue(s);
  }
}
Hamed
  • 5,867
  • 4
  • 32
  • 56