skip to Main Content

I really don’t understand how function passing works in Flutter.
When to use ()=> function(...); use this notation ?
I am trying to passing a function.This is my code:

        bottomSheetItem(context, 'İşlemi Sonlandır',
            () => _buildEvaluationBottomSheet(context)),
Widget bottomSheetItem(
    BuildContext context, String text, Function()? function) {
  return TextButton(
    onPressed: () {
      Navigator.pop(context);
      function;
    },
    child: Text(
      text,
      style: const TextStyle(fontSize: 12),
    ),
  );
}
_buildEvaluationBottomSheet(BuildContext context) {
  showModalBottomSheet(
    context: context,
    builder: (context) {
      return FractionallySizedBox(....);
    },
  );
}

Why this does not work ?
What are the optional function passing ways?

I tried to use function!; notation but I know that it doesnt work.
It must be function!();.
But why ?

2

Answers


  1. In your case:

    Widget bottomSheetItem(
        BuildContext context, 
        String text, 
        void Function()? function,
    ) {
      ...
    }
    

    you are trying to pass function(that could be null) without ANY params. but as function is nullable, you should use null checking and then call this function:

    ...
    return TextButton(
            onPressed: () {
              Navigator.pop(context);
              function?.call();
            },
            child: Text(
              text,
              style: const TextStyle(fontSize: 12),
            ),
          );
    ...
    

    more info: dart functions

    Login or Signup to reply.
  2. There is nothing wrong with the way you passed _buildEvaluationBottomSheet function.

    The problem is the way you called it on text button pressed, when you put function; it will not be called, instead you should call it like this:

    function?.call();
    

    The "?" is because your function can be null, so it will be called only when it is not null.

    As I said there is nothing wrong with the way you passed the _buildEvaluationBottomSheet function but you can improve it by directly pass it without using the expression "() =>"

    Here is how your complete code will look like:

    bottomSheetItem(context, 'İşlemi Sonlandır', _buildEvaluationBottomSheet);
      Widget bottomSheetItem(
          BuildContext context, String text, Function(BuildContext context)? function) {
        return TextButton(
          onPressed: () {
            Navigator.pop(context);
            function?.call();
          },
          child: Text(
            text,
            style: const TextStyle(fontSize: 12),
          ),
        );
      }
      _buildEvaluationBottomSheet(BuildContext context) {
        showModalBottomSheet(
          context: context,
          builder: (context) {
            return Container();
          },
        );
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search