Imagine that you have data that runs through your application, and you want your application to be able to update whenever that data changes.

It sounds like a nightmare to turn into, figuring out where the data has changed and manually updating the user interface in multiple places.

However, if you use ValueNotifier and ValueListenableBuilder widgets, you don’t have to do this manually.

Suppose you have a bunch of widgets scattered across the widget tree, all of which use the value of the same variable.

For simple variables like strings or integers, just wrap them in ValueNotifier,

ValueNotifier (0);Copy the code

It manages the state of the variable and notifies the port listening for it when its value changes.

ValueNotifier(42); ValueNotifier(43); ValueListenableBuilder<int>( valueListenable: value, builder: (context, value, _){ return Text('Value is $value'); });Copy the code

If you want to use this variable in software, you simply wrap it in ValueListenableBuilder.

ValueNotifier('Hello'); ValueListenableBuilder<String>( valueListenable: value, builder: (context, value, _){ return Text('$value'); });Copy the code

ValueListenableBuilder will listen for this variable and automatically rebuild its children when the value of the variable changes.

If you have more complex data, you can use the extended ValueNotifier to create custom notifiers for your data classes.

NotifyListeners must be called whenever data changes.

class MyNotifier extends ValueNotifier<MyDataClass> { MyNotifier(MyDataClass value) : super(value); void changeMyData(int i) { value.myInt = i; notifyListeners(); }}Copy the code

Flutter makes full use of the ValueListenable interface, especially for animation.

You can put the data into ValueListenablebuilders and use them in the animation class widgets.

ValueListenableBuilder(
    valueListenable: myAnimation,
    child: Container(
        width: 100, 
        height: 100,
        color: Colors.green,
    ),
    builder: (context, value, child) {
        return Transform.rotate(
            angle: MyAnimation.value * 2.0 * math.pi,
            child: child,
        );
    } 
)    
Copy the code

One last tip. Use inheritedWidgets to make your data accessible to all widgets in the Widget tree.

To learn more about ValueListenableBuilder, or other features of Flutter, visit Flutter. Dev

Video: Video address