Ooto
Ooto

Reputation: 1247

Flutter: How to pass function with arguments to child class

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)

Upvotes: 4

Views: 7263

Answers (2)

Suman Maharjan
Suman Maharjan

Reputation: 1122

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")

Upvotes: 3

The Chinky Sight
The Chinky Sight

Reputation: 390

You can do this way :

class Child extends StatefulWidget {
  final Function aFunction; 
  Child({this.aFunction});
  @override
  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.0),
      child: RefreshIndicator(child: Container(), onRefresh: widget.aFunction("Hello")),
    );
  }
}

Upvotes: 0

Related Questions