'ValueListenableBuilder to handle Map<int,String> Flutter

I want to modify a data (Map<int,String>)from a widget outside my data declaration. For example :

  class Home extends StatefulWidget {
    //...some code
    Map<int,String> myMap = {0:"Hi"};
    //...rest of the class

A new page child of Home :

class Menu extends StatefulWidget {
//...some code
myMap.clear();
//...rest of the class

How can I do this? I was reading something about ValueListenableBuilder can this help me? Obviously Map inside Home should be empty after clear() call.



Solution 1:[1]

you can do using function check here.



class HomePage extends StatelessWidget {
   HomePage();

  Map<int,String> myMap = {0:"Hi"};
  
  void onCalledFromOutside() {
    print("befor clear value");
    print(myMap);
    
    myMap.clear();
      print("after clear value");
    print(myMap);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
    child: ElevatedButton(
          onPressed: () { Navigator.of(context).push(
             MaterialPageRoute(
               builder: (context) => AnotherPage(onCalledFromOutside),
             ));
                        },
          child: const Text("Go to AnotherPage"),
        ),
      ),
    );
  }
}

class AnotherPage extends StatelessWidget {
  final Function callback;

  const AnotherPage(this.callback);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
    child: ElevatedButton(
           onPressed: callback as VoidCallback,
           child:const Text("Press me to clear Map"),
        ),
      ),
    );
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rohit Chaurasiya