flutter value Notifier

ValueNotifier is a unique subclass of Changenotifier that can hold a single value and alert widgets that are listening to it whenever that value changes. ValueNotifier extends Changenotifier.

ValueNotifier offers an easy and effective way to manage and update state in your application. making it a useful and lightweight tool for developing reactive data sources in Flutter.

When you need to update the UI due to changes in a value. ValueNotifier comes in handy. You can use a ValueNotifier for instance to keep track of changes to the value of a text field in a user interface . so that other UI elements can be updated to reflect the new value.

The main benefit of using a ValueNotifier over state management alternatives like setState or streams is that it is portable and simple to operate. It does not necessitate the creation of intricate streams and stream controllers, nor is it as resource-intensive as setState for straightforward use cases.

What is ValueNotifier?

Let’s first define ValueNotifier so that we can proceed to the specifics of how to use it in Flutter. A straightforward observable data model can be made using the class called ValueNotifier. It is a simplified version of the ChangeNotifier class, which forms the backbone of the reactive programming style used by Flutter. ValueNotifier has a single property named value that stores the model’s current value. The model alerts its listeners whenever its value changes. Due to this, it is simple to develop reactive Flutter applications, in which the UI is updated whenever the data changes.

How can ValueNotifier be used?

It’s very easy to use ValueNotifier in Flutter. You can create a ValueNotifier by providing it with an initial value. For instance , you  follow these steps to create a ValueNotifier that stores an integer value:

// syntax --> ValueNotifier<dataType> myValueNotifier = ValueNotifier<dataType>(value);

// Example :
ValueNotifier<int> myValueNotifier = ValueNotifier<int>(0);

In this example, we making a ValueNotifier that stores the value 0 as an integer.

When you have a use  ValueNotifier you can use the value property to read and modify its value. For instance you can follow these steps to read the value of the ValueNotifier:

Read the value of the ValueNotifier Object:

int currentValue = myValueNotifier.value;

ValueNotifier value property’s value can be modify by assigning  new value . For example the following steps can be used to update the ValueNotifier value to 100 :

myValueNotifier.value = 100;

The ValueNotifier notifier listeners updated whenever value is updated or changed . The addListener method can be used keep track of changes in ValueNotifier variable.

myValueNotifier.addListener(() {
  print('Value changed to ${myValueNotifier.value}');
});

In this example, we’re extending the myValueNotifier with a listener that prints a message whenever its value changes.

To build a basic data model that can be used to update the user interface, ValueNotifier is frequently used in Flutter widgets. ValueNotifier can be used in widgets by simply creating a new instance of it and passing it to the child widgets as necessary. Here’s a good example:

using ValueNotifier


class ValueNotifierExample extends StatelessWidget {
  ValueNotifierExample({Key? key}) : super(key: key);
  final ValueNotifier<int> myValueNotifier = ValueNotifier<int>(42);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.blue.shade900,title: const Text("Value notifier implement")),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Value: ${myValueNotifier.value}'),
          ElevatedButton(
            onPressed: () {
              myValueNotifier.value += 1;
            },
            child: const Text('Increment Value'),
          ),
        ],
      ),
    );
  }
}

Here is an example showing , how to create a ListView in Flutter using the ValueNotifier builder set:

import 'package:flutter/material.dart';

class ListViewValueNotifier extends StatefulWidget {
  const ListViewValueNotifier({super.key});

  @override
  _ListViewValueNotifierState createState() => _ListViewValueNotifierState();
}

class _ListViewValueNotifierState extends State<ListViewValueNotifier> {
  ValueNotifier<int> selectedIndex = ValueNotifier<int>(0);

  List<String> items = [
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5",
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue.shade900,
        title: const Text("ListView with ValueNotifier"),
      ),
      body: ValueListenableBuilder(
        valueListenable: selectedIndex,
        builder: (BuildContext context, int index, Widget? child) {
          return ListView.builder(
            itemCount: items.length,
            itemBuilder: (BuildContext context, int i) {
              return ListTile(
                title: Text(items[i]),
                selected: i == index,
                onTap: () {
                  selectedIndex.value = i;
                },
              );
            },
          );
        },
      ),
    );
  }
}

Conclusion 👍

ValueNotifier is a component of Flutter’s core Reactive Programming Model, which enables the creation of responsive and effective user interfaces. A ValueNotifier is a simple class that enables the development of reactive data sources that alert listeners when their values change.

ValueNotifier offers an easy and effective way to manage and update state in your application, making it a useful and lightweight tool for developing reactive data sources in Flutter.

Thanks for reading this article 💙…..

Have a beautiful day…..