Search code examples
flutterfunctiondartsyntaxcallback

Difference between myFunction, myFunction(), and myFunction.call() in Dart/Flutter


I've noticed that when I have a widget/class that takes Functions as arguments, when it comes time to call those functions, it can be done one of three ways (that I know of):

(Consider a Function, myFunction)

  1. myFunction

  2. myFunction()

  3. myFunction.call()

But the weird thing is, I've noticed that when using option 1), it will (ONLY SOMETIMES) not work and require the use of option 2 or 3 in order to work.

Why is that?

Specific example (I've verified the inconsistent calling behaviour with print debugging in the parent):

class SoundPickerTile extends StatelessWidget {
  final Sound sound;
  final Function() checkboxCallback;
  final Function() soundPlayCallback;

  SoundPickerTile(
      {required this.sound, required this.checkboxCallback, required this.soundPlayCallback});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: checkboxCallback, // <--------------- Function executes in parent
      child: Container(
        color: sound.isIncluded ? Colors.lightGreen.withAlpha(100) : Colors.white,
        child: Padding(
          padding: EdgeInsets.fromLTRB(20, 10, 0, 10),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  sound.shortTitle,
                ),
              ),
              Expanded(
                child: IconButton(
                  icon: Icon(Icons.play_circle_outline),
                  onPressed: () {
                    print("this line of code was reached"); // this works
                    soundPlayCallback; // <--------------- Function *does not* execute in parent
                  },
                ),
              ),

            ],
          ),
        ),
      ),
    );
  }
}

Solution

  • In the GestureDetector we use:

    onTap: checkboxCallback, 
    

    without the (), since that would call the function immediately, we don't want to call the function, we just want to pass a reference to the function on what should happen when onTap is called.

    Then with:

    onPressed: () {
                        print("this line of code was reached"); // this works
                        soundPlayCallback; // <--------------- Function *does not* execute in parent
                      },
    

    Since were are not using () it's not being called it's just a reference to the function. Instead, what you can do is: onPressed: soundPlayCallback; Or add the ()

    Edit.

    What is the difference between calling the function without parentheses and with parentheses