Home > Blockchain >  How to Call a function in parent widget from child widget | Flutter
How to Call a function in parent widget from child widget | Flutter

Time:11-19

I have a parent and child widget. The parent widget has a function. I want to call that function (myParentFunction) from my child widget. This is the parent widget,

class ParentWidget extends StatelessWidget {

  void myParentFunction() {
    print("This is print from parent");
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: MyCustomButton(),
    );
  }
}

This is the child widget

class MyCustomButton extends StatelessWidget {

  void myChildFunction() {
    print("This is print from child");
    //Here i want to call the myParentFunction()
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: Text('Press'),
      onPressed: () {
        newFunction();
      },
    );
  }
}

Here the expected result is when i press the 'Press' button i want the output as This is print from child This is print from parent. How i rewrite this code to get that functionality.

CodePudding user response:

you should pass the function and call in child widget

class ParentWidget extends StatelessWidget {

  void myParentFunction() {
    print("This is print from parent");
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: MyCustomButton(myParentFunction),
    );
  }
}

class MyCustomButton extends StatelessWidget {

final Function onTap;

MyCustomButton(this.onTap);
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: Text('Press'),
      onPressed: onTap,
    );
  }
}

CodePudding user response:

Use a callBack Funtion


class ParentWidget extends StatelessWidget {
  void myParentFunction() {
    print("This is print from parent");
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: MyCustomButton(
        callback: () {
          myParentFunction();
        },
      ),
    );
  }
}

class MyCustomButton extends StatelessWidget {
  final VoidCallback callback;
  MyCustomButton({
    Key? key,
    required this.callback,
  }) : super(key: key);
  void myChildFunction() {
    print("This is print from child");
    //Here i want to call the myParentFunction()
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: Text('Press'),
       onPressed: () {
        callback();
      },
    );
  }
}
  • Related