I need have this function in a parent widget
User? _user;
void _onChangeUser(User? user) {
setState(() {
_user = user;
});
}
I want to pass it to a child widget that receives a function with a dynamic argument, so on the parent widget build method I do:
return _ChildView(
onPress: _onChangeUser,
);
And on my child widget I want to pass this function, but let it have a dynamic argument, like this:
class _ChildView extends StatelessWidget {
const _ChildView({
Key? key,
required this.onPress,
}) : super(key: key);
final ValueChanged<dynamic> onPress;
However, flutter is not allowing this. The argument type ‘void Function(User?)’ can’t be assigned to the parameter type ‘void Function(dynamic)’. I would expect to be able to assign a User? to a dynamic value.
How do I go about this?
I have also tried
final Function(dynamic) onPress;
but it doesn’t work either
2
Answers
Your function inside
_ChildView
has a typedynamic
as parameter, instead your function_onChangeUser
has a type ofUser?
as a parameter.If you want the
onPress
function inside_ChildView
to accept arguments of different types each time it is called, you can define it to accept a generic typeT
as follows:Change
to a general Function type
and call it with