user3234809
user3234809

Reputation: 77

Flutter: How to set state of parent widget

I'd like to change the color of a parent container with a button from a child widget. Let's say I have a parentClass widget and a childClass widget. The container with dynamic color is in parentClass, and the button is in childClass. At first the container is blue and I want to make it red on button tap.

Color dynamicColor;

class ParentClass extends StatefulWidget {
  ParentClass({Key key}) : super(key: key);

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

class _ParentClassState extends State<ParentClass> {
  @override
  void initState() {
    super.initState();
    setState(() {
      dynamicColor = Colors.blue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ChildClass(),
        Container(
          color: dynamicColor,
          child: ...
        )
      ],
    );
  }
}

class ChildClass extends StatefulWidget {
  ChildClass({Key key}) : super(key: key);

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

class _ChildClassState extends State<ChildClass> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextButton(
        onPressed: () {
          setState(() {
            dynamicColor = Colors.red; // What I want to do
          });
        },
        child: Text('Change parent container color'),
      ),
    );
  }
}

Upvotes: 2

Views: 909

Answers (1)

Roger M. Brusamarello
Roger M. Brusamarello

Reputation: 91

You can create a function on parent widget and pass to child with parameter. Like:

void changeColor() async {
  setState(() {
    dynamicColor = Colors.blue;
  });
 }

on your Widget Tree

 CustomChild(function: () => changeColor()),

Your custom Widget

class CustomChild extends StatelessWidget {
  Function function;
  CustomChild({this.function})
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Upvotes: 3

Related Questions