0

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.

Taha Kerrouzi
  • 177
  • 2
  • 15

2 Answers2

1

You need to use Function()? instead of Function? as the type of onPress variable because onTap requires a GestureTapCallback which is typedef for a Function().

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),
        ),
      ),
    );
  }
}
Tirth Patel
  • 5,443
  • 3
  • 27
  • 39
1

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.

zpouip
  • 787
  • 5
  • 11