Martin Pellicer
Martin Pellicer

Reputation: 119

Future Function passed as parameter not executing Flutter

I am trying to create a widget from a custom Widget, so when I pass the parameters to the function that creates the Widget I need to set the onPressed function but dosen´t work when pressing it.

Class A:

final Future Function(BuildContext context, Key newKey, String title) myFunction = _functionToPass;
setState(() {
    _widgetList.add(_MyCustomWidget.createCustomWidget(_title, _isChecked, myFunction));
  });//This works, the widget appears on my screen.

  Future _functionToPass(BuildContext context, Key newKey, String taskTitle) =>
  showDialog(......);  
  

Class B:

class MyCustomWidget {
  StatefulBuilder createCustomWidget(title, isChecked, myFunction) {
    return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return ListTile(
            title: Text(title),
            leading: Checkbox(
              value: isChecked,
              onChanged: (bool? newValue) {
                setState(() {
                  isChecked = newValue!;
                });
              },
            ),
            trailing: TextButton(
              child: Icon(Icons.edit),
              onPressed: () async {
                print("Hi"); //This is printing correctly
                await myFunction; //the function is not calling
              },
            ),
          );
        });
  }
}

Upvotes: 1

Views: 2068

Answers (1)

George Rappel
George Rappel

Reputation: 7198

Solution

You need to call your function by adding the parentheses to it, and passing the required parameters:

onPressed: () async {
  print("Hi");
  await myFunction(param1, param2...);   //Change this line
},

Sample for Reproducing the Issue:

Try running the code below on dartpad.dev, with and without the parentheses:

void main() async {
  final Future Function(String title) myFunction = (String title) async{print(title);};
  print("Hi");
  await myFunction("a");
}

Also, as discussed in the comments, it's a good practice to specify the expected function with parameters on the method handle, instead os just naming the parameters, add the type, like this:

StatefulBuilder createCustomWidget(title, isChecked, Future Function(BuildContext, Key, String) myFunction)

So when you pass the wrong parameters, Dart knows it is wrong and warns you:

Sample error with wrong parameters

Upvotes: 2

Related Questions