0

I'm trying to do the exact same thing that poster in the following question about passing a function to the State of a a Stateful widget: Accessing a function of stateful widget in its state class? flutter

In this example (same one I'm working on and likely from the same youtube video), how do I move the function down to the stateful state section and passing the two parameters through the stateful constructor?

Would appreciate any help!

PJQuakJag
  • 1,067
  • 4
  • 16
  • 35

1 Answers1

0

You can pass the function callback to the StatelessWidget during initialization. That's my approach on initializing an ActionMenu that calls its functions from the parent class.

late ActionMenu actionMenu;

@override
void initState() {
  super.initState();
  // Initialize ActionMenu
  // arguments passed are Home Screen functions
  // that can be in ActionMenu class
  actionMenu = ActionMenu(this.settings, this.logout);
}

settings(){
  // TODO
}

logout(){
  // TODO
}

...and on the ActionMenu. You can now call the functions inside the StatelessWidget.

enum MenuOptions { menuSettings, menuLogout }

class ActionMenu extends StatelessWidget {
  final Function menuSettings, menuLogout;
  ActionMenu(this.menuSettings, this.menuLogout);

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<MenuOptions>(
      onSelected: (MenuOptions value) {
        switch (value) {
          case MenuOptions.menuSettings:
            this.menuSettings();
            break;
          case MenuOptions.menuLogout:
            this.menuLogout();
            break;
        }
      },
      itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[
        PopupMenuItem<MenuOptions>(
          value: MenuOptions.menuSettings,
          child: Text('Settings'),
        ),
        PopupMenuItem<MenuOptions>(
          value: MenuOptions.menuLogout,
          child: Text('Logout'),
        ),
      ],
    );
  }
}
Omatt
  • 8,564
  • 2
  • 42
  • 144