I wanted to create a generic call back function for a button in Flutter. I want that it takes generic type as argument so that I can use it with different types. I tried to create is like this.
class GenericButtonWidget extends StatelessWidget {
const GenericButtonWidget({Key? key, this.save, this.delete}) : super(key: key);
final Function<T>(T)? save;
final Function<T>(T)? delete;
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
InkWell(
onTap: () => save,
child: Text('Save'),
),
InkWell(
onTap: save, //error here
child: Text('Delete'),
),
],
),
);
}
}
}
Error is : The argument type 'dynamic Function(dynamic)?' can't be assigned to the parameter type 'void Function()?'
I need guidance because I do not know, I am doing it right or wrong. Thanks.
What you are trying to do does not work. The generic variable needs to decide on a type and continue with that. What you are trying to do is to be able to assign to it different types in the future, which is not how generics work. The dynamic
type is what you are looking for as suggested in the other answer here.
I'm not sure why you want this. Having strong types is preferable to dynamic types as it reduces bugs and gives you piece of mind.
Having said that, this works
Function<T>(T a) save = <T>(T a) {
print(a);
return a;
};
void main() {
save(5);
}
but this does not, because of the same error you mentioned.
Function<T>(T a) save = (int a) {
print(a);
return a;
};
void main() {
save(5);
}
So the caller in your example could potentially be generic as well, and could decide on the generic parameter of save here that way, maybe.