Flutter setstate of another widget

Flutter setState of Another Widget

In Flutter, the setState method is used to update the state of a widget and rerender its UI. However, setState can only be called from within the widget that owns the state. Therefore, if you want to update the state of another widget, you need to lift the state up to a common ancestor widget.

Let’s say we have two widgets: ParentWidget and ChildWidget. And we want to update the state of the ChildWidget from the ParentWidget. Here’s how you can achieve it:

  
  class ParentWidget extends StatefulWidget {
    @override
    _ParentWidgetState createState() => _ParentWidgetState();
  }
  
  class _ParentWidgetState extends State {
    bool _childWidgetState = false;
  
    void updateChildWidgetState(bool newState) {
      setState(() {
        _childWidgetState = newState;
      });
    }
  
    @override
    Widget build(BuildContext context) {
      return Column(
        children: [
          ChildWidget(childWidgetState: _childWidgetState),
          RaisedButton(
            onPressed: () {
              updateChildWidgetState(true);
            },
            child: Text('Update Child Widget State'),
          ),
        ],
      );
    }
  }
  
  class ChildWidget extends StatelessWidget {
    final bool childWidgetState;
  
    ChildWidget({this.childWidgetState});
  
    @override
    Widget build(BuildContext context) {
      return Text(childWidgetState ? 'Child Widget State is true' : 'Child Widget State is false');
    }
  }
  
  

In the above example, we have a ParentWidget that maintains the state of the ChildWidget. The ParentWidget has a boolean variable _childWidgetState, which is initially set to false. We pass this state as a parameter to the ChildWidget.

When the “Update Child Widget State” button is pressed, it calls the updateChildWidgetState method, which in turn calls setState and updates the _childWidgetState to true. This triggers a rebuild of the ParentWidget and updates the UI of the ChildWidget accordingly.

Leave a comment