How can I assign an argument of type 'Function' to a parameter of type 'void Function()'?

Viewed 7763

I'm trying to create a stateless widget like this:

import 'package:flutter/material.dart';

class Answers extends StatelessWidget {
  final Function nextQuestion;

  Answers(this.nextQuestion);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: nextQuestion,
      child: Text("Answer"),    
    );
  }
}

However, an error appears in the onPressed argument: "The argument type 'Function' can't be assigned to the parameter type 'void Function()?'". How can I solve it?

3 Answers

Just change the type of nextQuestion to void Function():

final void Function() nextQuestion;

changing

  final Function nextQuestion;

to

final VoidCallback nextQuestion;

This solved my issue.

Change type of nextQuestion to VoidCallback which can be used if you have a function which returning no data with no arguments. change your datatype from Function to VoidCallback.

final VoidCallback nextQuestion;

       or you can put anonymous function in front of onPressed (){}

onPressed: ()=>nextQuestion,

Related