Flutter default value for a Function

Viewed 2502

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

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;

just change

final Function onPress;

to

final Function() onPress;
  • For nullable function, use ?

    class FooWidget extends StatelessWidget {
      final Function? onPressed; // <-- Nullable, use '?'
    
      FooWidget({
        this.onPressed,
      });
    
      // ... 
    }
    
  • For non-nullable function, use required

    class FooWidget extends StatelessWidget {
      final Function onPressed; // <-- Non-nullable
    
      FooWidget({
        required this.onPressed, // <-- Use 'required'
      });
    
      // ...
    }
    
Related