Flutter correct way to provide a callback function to a stateless widget

Viewed 67

I have a stateless widget ( a side panel). When some button on side panel is pressed, it is supposed to call a function which is in its parent stateful widget. This function has an input type String.

My call back function is:

    sidePanelTapped(String option){
        switch (option){
          case NEW : {
            if (kDebugMode) print('TappedOption = 1');
            setState(() => tappedOption=1);
          } break;
          case PROGRESS : {
            if (kDebugMode) print('TappedOption = 2');
            setState(() => tappedOption=2);
          } break;
.
.
.

My stateless widget has this format:

class SidePanel extends StatelessWidget {
  final Function funct;
  final int tappedOption;
  SidePanel({required this.funct, required this.tappedOption});

Then in my build section my code is as follows:

.
.
.
Container(
                          margin: EdgeInsets.only(bottom: 5.0),
                          child: GestureDetector(
                            onTap: ()=>funct(optionEntry.key),
                            child: ListTile(
                              minVerticalPadding: 1.0,
                              tileColor: optionEntry.key == NEW
                                  ? tappedOption == 1? Colors.grey[200] 
.
.
.

The problem is that my side panel is not changing state as it is suppose to. What am I doing wrong here?

1 Answers

First add a VoidCallback:

class SidePanel extends StatelessWidget {
    final Function funct;
    final int tappedOption;
    final VoidCallback onTap;

    SidePanel({
        required this.funct,
        required this.tappedOption,
        required this.onTap,
    });

then change:

onTap: ()=>funct(optionEntry.key)

to

onTap: onTap,

then pass the function funct(optionEntry.key) when calling the SidePanel, like this.

onTap: () {
    funct(optionEntry.key);
}
Related