Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Update child state from parent

I would like to update a child's state when a button is clicked in the parent, so for example:

class Parent extends StatelessWidget{
    Widget build(context){
    return Scaffold(
            appBar: AppBar(
                actions: <Widget>[
                    IconButton(
                            onPressed: () => //somehow increment the child's counter,
                            icon: const Icon(Icons.add),
                        ),
                    
                ],
            ),
            body: const Child(),
        );
    }
}

class Child extends StatefulWidget {
    const Child({Key? key}) : super(key: key);

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

class _ChildState extends State<Child> {
...
   int counter = 0; //to be incremented when parent's button is clicked on.
...
}

Is there a common way to implement this? From the other posts I've read, people usually use the child to update the parent's state via callback, so if there is a way to refactor my code to acheive the same effect, that would help too.

like image 423
goldenotaste Avatar asked Oct 19 '25 05:10

goldenotaste


1 Answers

You can create the field counter in the parent and pass it down to the child widget and update the child widget from the parent.

You can check the demo that I made here.. DartPad Demo Link

like image 58
Meet Prajapati Avatar answered Oct 22 '25 05:10

Meet Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!