Search code examples
flutterdartflutter-layout

Argument type 'Function' can't be assigned to the parameter type 'void'


I am passing a call back function from my child file to the parent file, in the elevated button class, I am passing the function in the class (in the child file )to the named parameter on pressed, but I am getting the error in the question above, while it worked for the tutorial I am using(academind). How do I solve this?

CHILD file

class Answer extends StatelessWidget {

  final Function selectHandler;

  Answer(this.selectHandler);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: ElevatedButton(
        child: Text('Answer 1'), 
        style: ElevatedButton.styleFrom(
          primary: Colors.lightGreen
        ),
        onPressed: selectHandler, 
      ),
    );
  }
}

PARENT file

// ignore_for_file: prefer_const_constructors, avoid_print, prefer_const_literals_to_create_immutables, must_be_immutable, prefer_const_constructors_in_immutables
import 'package:flutter/material.dart';

import './question.dart';
import './answer.dart';

void main() => runApp(MyApp());


class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // ignore: todo
    // TODO: implement createState
    return _MyAppState();
  }
}

class _MyAppState  extends State <MyApp>{
  var _questionsIndex = 0;
  var questions = [
      'What\'s your favourite book',    
      'What\'s your favourite colour',
      'What\'s our favourite poem',
    ];
  void _answerQuestion() {
    setState(() { 
      _questionsIndex = _questionsIndex + 1;
      if (_questionsIndex >= questions.length) _questionsIndex = 0;
    });
    
    print(_questionsIndex);
    print(questions.length);
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('My First App'),),
        body: Column(
          children: [
            Question(
              questions[_questionsIndex],
              ),
            Answer(_answerQuestion),
            Answer(_answerQuestion),
            Answer(_answerQuestion),
          ],
        )
      ),
    );
  }
}

Solution

  • Change Function to

    void Function functionName(){}
    

    or

    VoidCallback functionName(){}