Search code examples
flutterdartfirst-class-functionsfirst-class

what is the different between Function first class and void function in Dart


in order to optimize my code, I try to use Function first class in the onTap property of the GestureDetector widget, like in the code below:

 import 'package:flutter/material.dart';

class ReusableCard extends StatelessWidget {
  final Color colour;
  final Widget? childCard;
  final Function? onPress;
  ReusableCard({required this.colour,this.childCard,this.onPress}) ;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress,
      child: Container(
        child: childCard,
        margin: EdgeInsets.all(15.0),
        decoration: BoxDecoration(
          color: colour,
          borderRadius:BorderRadius.circular(10.0),
        ),
      ),
    );
  }
}

but I got that error: The argument type 'Function?' can't be assigned to the parameter type 'void Function()?'.

hope that someone can explain what going on here and thank you previously.


Solution

  • Use VoidCallback? in this case instead of Function?.

    In the end, VoidCallback is defined as typedef VoidCallback = void Function() so you can even end up using Function()? but this is a cool shortcut.