Flutter default value for a Function

Issue

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,
        ),
      ),
    );
  }
}

Solution

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;

Answered By – Nidheesh MT

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *