Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to pass function with arguments to child class

Tags:

flutter

dart

How can I pass a function with argument to child class in Flutter?

My current code is like below.

parent.dart

class _ParentState extends State<Parent> {
    int _currentIndex = 0;

    Widget callPage(int currentIndex) {
      switch (currentIndex) {
        case 0:
         return Child(
          aFunction: _aFunction('hello')
        );
      case 1:
        return Child1();
      case 2:
        return Child2();
      default:
        return Child();
      }

    }

  @override
  Widget build(Buildcontext context) {
      ...
  }

  Future<void> _aFunction(String arg) async {
      ...
  }
}

child.dart

class Child extends StatefulWidget {
    final Function(String hello) aFunction;

    Child({this.aFunction});
}


...

class _ChildState extends State<Child> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.0),
      child: RefreshIndicator(
        onRefresh: widget.aFunction, // How can I refer to the argument here?

I don't know how to do it but I tried this way anyway, and there is an error in Parent class. It says

The argument type Future can't be assigned to the parameter type 'dynamic Function(String)

like image 326
Ooto Avatar asked Oct 28 '25 16:10

Ooto


1 Answers

Just pass the reference of the function as shown below. You don't have to add the string parameter _aFunction("hello").

Widget callPage(int currentIndex) {
      switch (currentIndex) {
        case 0:
         return Child(
          aFunction: _aFunction
        );
      case 1:
        return Child1();
      case 2:
        return Child2();
      default:
        return Child();
      }

    }

Then you can call the function from the child widget as

RefreshIndicator(child: Container(), onRefresh: widget.aFunction("Hello")
like image 192
Suman Maharjan Avatar answered Oct 31 '25 10:10

Suman Maharjan