Difference Between ChangeNotifier and ValueNotifier

Created At: 2022-05-18 07:33:17 Updated At: 2022-05-18 19:54:22

Here we will learn the difference between ChangeNotifier and ValueNotifier. 

Generally speaking with ChangeNotifier, you need more code. With ValueNotifier much less code. 

But ValueNotifier only works with one value which causes one rebuild of the widget. Within change notifier you can have multiple values that would trigger UI build.

For ValueNotifier you will use ValueLisenableBuilder rather than Consumer widget which we use for ChangeNotifier.

See the complete code

Code for notifier controller

class MyProviderController extends ValueNotifier{

  MyProviderController(super.value);

  void incrementValue(){
    value++;
  }

}

Code for main.dart

import 'package:flutter/material.dart';
import 'package:provider_diff/my_provider_controller.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyProvider(),
    );
  }
}

class MyProvider extends StatelessWidget {
  const MyProvider({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    MyProviderController counter = MyProviderController(0);

    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ValueListenableBuilder(
            builder: (_, myProvider, child){
              return Center(child: Text('Current value is '
                  '$myProvider')
              );
          }, valueListenable: counter,),
          TextButton(
              onPressed: ()=>counter
                  .incrementValue(),
              child: const Text("Tap me"))
        ],
      ),
    );
  }
}

When you want to work a on single value change  use valueNotifier. It makes your code faster to run, Since you only work on one widget to rebuild. It's bound to a widget, rather than whole widget tree.

Comment

Add Reviews