Home > Enterprise >  can I insert an if statement into the setState of a child Stateful Widget from the parent widget?
can I insert an if statement into the setState of a child Stateful Widget from the parent widget?

Time:01-17

I have a stateful widget button that is repeated many times in my app. one of the buttons though, is exactly the same as the others but has an additional if statement in it's setState.

Is it possible to insert that additional if statement into the setstate when the widget is called from the parent widget? and if so, what is the type of building block to use? e.g final VoidCallback? ... or final fuction ... etc

I know I can insert the full Setstate method using VoidCallback? or Function bit there are many if statements and many buttons which would seem like a lot of repeated code.

the other option is to replicate the widget and add that if statement in but again I feel like its just more replicated code.

thanks so much and any help would be greatly appreciated.

CodePudding user response:

Yes, it is possible to insert an if statement into the setState method of a child StatefulWidget from the parent widget. One way to do this is to pass a callback function as a parameter to the child widget, which can be called from the parent widget when the button is pressed.

For example, in the parent widget, you can define a function that contains the logic for the additional if statement and pass it as a parameter to the child widget:

class _ParentWidgetState extends State<ParentWidget> {
  void _onButtonPressed() {
    // Additional if statement logic here
  }

  @override
  Widget build(BuildContext context) {
    return ChildWidget(onButtonPressed: _onButtonPressed);
  }
}

Then in the child widget, you can call the callback function in the setState method:

class ChildWidget extends StatefulWidget {
  final VoidCallback onButtonPressed;

  ChildWidget({required this.onButtonPressed});

  @override
  _ChildWidgetState createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  @override
  Widget build(BuildContext context) {
    return FlatButton(
      onPressed: () {
        setState(() {
          // Additional if statement logic here
          widget.onButtonPressed();
        });
      },
      child: Text('Button'),
    );
  }
}
  • Related