Reputation: 21
I try to use a function in a widget but i recive this error Error: The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.
I search here and see that someone suggest to use the same metod that I set in my code so what's the problem?
import 'package:flutter/material.dart';
class ReusableCard extends StatelessWidget {
ReusableCard(
{required this.colour, required this.cardChild, required this.onPress});
final Color colour;
final Widget cardChild;
final Function onPress;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPress,
child: Container(
child: cardChild,
margin: EdgeInsets.all(15.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: colour,
),
),
);
}
}
Upvotes: 0
Views: 889
Reputation: 2087
By default, the Function
type is a dynamic-type-value-returning Function with no parameters.
Typically, Flutter expects void callbacks inside its buttons, which means it expects a void Function
type, with no arguments.
A common, flexible and readable way to work around this is to wrap your function with a void function, like:
() => myFunction()
This would work even if your function is very different (e.g. it has some arguments), making your code more flexible.
() => myFunctionThatAcceptsAnInteger(5)
Upvotes: 1
Reputation: 1487
In Flutter we already have the signature of callbacks that have no arguments and return no data - VoidCallback.
You can use it:
final VoidCallback onPress;
Also, we have ValueSetter<T>, ValueGetter<T>
, and others.
foundation-library
Upvotes: 1