Code down here keeps telling me that there's a problem in the syntax here onTap: onPress,
import 'package:flutter/material.dart';
class ReusableCard extends StatelessWidget {
final Color color;
final Widget? cardChild;
final Function? onPress;
ReusableCard({ this.cardChild, required this.color, this.onPress});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPress,
child: Container(
margin: const EdgeInsets.all(15.0),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(15.0),
),
child: cardChild,
),
);
}
}
CodePudding user response:
Use voidcallback
class ReusableCard extends StatelessWidget {
final Color color;
final Widget? cardChild;
final VoidCallback onPress;//here
ReusableCard({ this.cardChild, required this.color, this.onPress});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPress,
child: Container(
margin: const EdgeInsets.all(15.0),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(15.0),
),
child: cardChild,
),
);
}
}
or you can also do this
class ReusableCard extends StatelessWidget {
final Color color;
final Widget? cardChild;
final Function? onPress;
ReusableCard({ this.cardChild, required this.color, this.onPress});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){onPress();},//create a method and call onPress here
child: Container(
margin: const EdgeInsets.all(15.0),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(15.0),
),
child: cardChild,
),
);
}
}
CodePudding user response:
Function is null type, so it can be null.
You should write
onTap:(onPress!=null) ? onPress : null
CodePudding user response:
Using final Function? onPress;
is defined nullable function.
But onTap
requires void function,
You can just do
final Function()? onPress;
Or
onTap: () {
if (onPress != null) onPress!();
},
Using VoidCallback
/// Signature of callbacks that have no arguments and return no data.
typedef VoidCallback = void Function();
Hope you get the issue here. Also provide key on constructor.
class ReusableCard extends StatelessWidget {
final Color color;
final Widget? cardChild;
final Function()? onPress;
const ReusableCard({
this.cardChild,
required this.color,
this.onPress,
super.key,
});
But I think it is pretty to use final GestureTapCallback? onPress;