Search code examples
flutterdart

valuelistenablebuilder for ValueNotifier<Map<dynamic, dynamic>>


I came to know that we cannot refresh the state of the class using valuestatebuilder. This is very unfortunate for me. Because after weeks of hardwork i am finally on the verge to complete my first flutter app/

The problem: I want to update the state of the mainclass. Map is stored in another. I have tried both: setstate and valuenotifier but all in vain. Can someone please tell me how to overcome this problem and how to use listenablebuilder to update the main class? thanks.

Example Code:

// class where the map<> is located.
// totalBill is the variable i want to use the value of in the next class
    var totalBill = ValueNotifier({});
    Map billl = {};
    int temp = 0;
    
    class ReusableCard extends StatefulWidget {
      ReusableCard({
        required this.itemName .....
...
...
// down in the class:
return GestureDetector(
      onTap: () {

        setState(() {
          totalBill.value[widget.itemName] = temp;
        });
      },

then in the next class:

ValueListenableBuilder<Map>(
// totalBill is being borrowed from the above example / class 
                    valueListenable: totalBill,
                    builder: (context, val, _) {
                      //print(val);
                      //print(itemsInList);

                      return Column(
                        children: [
                          Text(val.toString()),
.... 
...

I will appreciate any help.


Solution

  • ValueNotifier only notifies when the value is changed. In case of Map, value is reference. Which won't be changed if the value inside it is changed.

    Fix

    Change the onTap function to the following

    onTap((){
    
      totalBill.value[widget.itemName] = temp; // or change the value to whatever you want   
      totalBill.notifyListeners() // this notifies to all the listeners. 
    
    });
    

    For more : https://github.com/flutter/flutter/issues/29958