Provider ValueNotifier listen not working on some Pages on Flutter

Issue

listen is not working. when hot reload value is updated.

Page A

  @override
  Widget build(BuildContext context) {

    ValueNotifier<List<ProductModel>> selectNotifier = Provider.of<ValueNotifier<List<ProductModel>>>(context, listen: true);

Widget

 Text('${selectNotifier.value.length}'),

Page B

 InkWell(
     onTap: () {
         selectNotifier.value.add(selectProduct);                        
     },

main.dart

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<ValueNotifier<List<ProductModel>>>(
          create: (_) => ValueNotifier<List<ProductModel>>([]),
        ),
      ],
      child: MaterialApp(
        theme: CustomTheme.themeData,
        onGenerateRoute: Router.generateRoute,
        debugShowCheckedModeBanner: false,
      ),
    );
  }

Version

provider: ^4.1.2

Flutter Version

1.17.2

I tried below ways to fix this issue. But I don’t know what is right way(best way).

1st way

After downgrade Flutter and Provider, now is working. why is that?

provider: 3.2.0
git checkout v1.12.13-hotfixes

2nd way

Or it is working this way too.//but warning on the IDE

onTap: () {
             selectNotifier.value.add(selectProduct); 
             selectNotifier.notifyListeners(); //info: The member 'notifyListeners' can only be used within instance members of subclasses of 'package:flutter/src/foundation/change_notifier.dart'.                      
         },

But warning disappear, after adding this ChangeNotifier,

class _viewState extends State<View> with ChangeNotifier{

and also getting error after adding ChangeNotifier

The following assertion was thrown while finalizing the widget tree:
_CartItemViewState.dispose failed to call super.dispose.

dispose() implementations must always call their superclass dispose()
method, to ensure that all the resources used by the widget are fully
released.

3rd way

I don’t get any issue on this way, but I used so many ValueNotifier in my production app, so, others are not a List. I don’t know how to change other types.

 onTap: () {
        selectNotifier.value = List.from(selectNotifier.value)..add(widget.productModel);
}

Solution

In this question, 3rd way is the correct way.

onTap: () {
        selectNotifier.value = List.from(selectNotifier.value)..add(widget.productModel);
}

Answered By – BIS Tech

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *