Flutter default value for a Function
968
Solution 1
You can make them nullable fields as follows
ReusableCard({required this.cardColor, this.cardChild, this.onPress});
final Color cardColor;
final Widget? cardChild;
final VoidCallback? onPress;
Solution 2
just change
final Function onPress;
to
final Function() onPress;
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on December 29, 2022Comments
-
Admin over 1 year
I am currently learning a course on Flutter. They provide you with an old stub project (nullable). When I try to migrate to Flutter 2.12.0 or higher - null safety kicks in. I have a basic understanding on how it works - but this I cannot find anywhere on Google or StackOverFlow.
I have a custom Card widget. It requires a Color parameter. Also I need it to be able to receive a Widget child parameter as well as an onPress Function, but I don't want to make them required. Please, help. How do I create a default value for Widgets and Functions?
class ReusableCard extends StatelessWidget { ReusableCard({@required this.cardColor, this.cardChild, this.onPress}); final Color cardColor; final Widget cardChild; final Function onPress; @override Widget build(BuildContext context) { return GestureDetector( onTap: onPress, child: Container( child: cardChild, margin: EdgeInsets.all(10.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: cardColor, ), ), ); } }