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
In your case:
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:
more info: dart functions
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:
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: