skip to Main Content

I try to use a function in a widget but i recive this error
Error: The argument type ‘Function’ can’t be assigned to the parameter type ‘void Function()?’.

I search here and see that someone suggest to use the same metod that I set in my code so what’s the problem?

import 'package:flutter/material.dart';

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

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

4

Answers


  1. change final Function onPress; to final Function() onPress;

    Login or Signup to reply.
  2. Replace onTap: onPress with onTap: () => onPress()

    Login or Signup to reply.
  3. In Flutter we already have the signature of callbacks that have no arguments and return no data – VoidCallback.

    You can use it:

    final VoidCallback onPress;
    

    Also, we have ValueSetter<T>, ValueGetter<T>, and others.
    foundation-library

    Login or Signup to reply.
  4. By default, the Function type is a dynamic-type-value-returning Function with no parameters.

    Typically, Flutter expects void callbacks inside its buttons, which means it expects a void Function type, with no arguments.

    A common, flexible and readable way to work around this is to wrap your function with a void function, like:

    () => myFunction()

    This would work even if your function is very different (e.g. it has some arguments), making your code more flexible.

    () => myFunctionThatAcceptsAnInteger(5)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search