skip to Main Content

I have a scenario where I have a button in the GrandChild widget that updates a variable and "sends" the updated variable to the Child.The child uses the variable it receives ,ie its used in another variable in the Child widget.The Child consequently also updates a variable and pushes it to the Parent.I am wondering if its possible to update all the variables by just one tap of a button in the GrandChild widget.

here is my GrandChild:

class GrandChild extends StatefulWidget {
  Function(int) changeNumber;
  GrandChild(this.changeNumber, {super.key});

  @override
  State<GrandChild> createState() => _GrandChildState();
}

class _GrandChildState extends State<GrandChild> {
  int counter = 0;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
        onPressed: () {
          setState(() {
            ++counter;
            widget.changeNumber(counter);
          });
        },
        child: const Text('Update all'));
  }
}

here is my Child:

class Child extends StatefulWidget {
  Function(int) updateParent;//I think this will be needed to update parent
  Child(this.updateParent, {super.key});

  @override
  State<Child> createState() => _ChildState();
}

class _ChildState extends State<Child> {
  int childCounter = 0;
  int multiple = 1;
  int amountInChild = 0;

  fromGrandChild(int newChildCounter) {
    setState(() {
      childCounter = newChildCounter;
    });
  }

  @override
  Widget build(BuildContext context) {
    amountInChild = childCounter * multiple;//this is what I need to update in parent
    return GrandChild(fromGrandChild);
  }
}

here is Parent:

class Parent extends StatelessWidget {
   Parent({Key? key}) : super(key: key);
  int amountInParent = 0;
  receiveFromChild(int newFromChld) {
    amountInParent = newFromChld;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Child(receiveFromChild),
          Text(amountInParent.toString())
        ],
      ),
    );
  }
}

I do not wish to include another button in Child to update Parent, only the elevated button in GrandChild to update everywhere.

I have used call back function in GrandChild.

2

Answers


  1. I’m not sure if I fully understand your question, but I believe all that’s needed now is to call the updateParent in fromGrandChild. So

      fromGrandChild(int newChildCounter) {
        setState(() {
          childCounter = newChildCounter;
        });
        widget.updateParent(newChildCounter); //or whatever value you want to pass.
      }
    
    Login or Signup to reply.
  2. Actually what you can do is to declare a function in parent and pass this function to child and then to grandchild and there you can update any value of you want

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search