flutter 参数类型“Function”不能分配给参数类型“void”

gstyhher  于 2022-12-19  发布在  Flutter
关注(0)|答案(3)|浏览(162)

我在提升的按钮类中从我的子文件向父文件传递一个回调函数,我在类中(在子文件中)传递函数给按下时命名的参数,但是我得到了上面问题中的错误,而它在我使用的教程(academind)中是有效的。我该如何解决这个问题?
子文件

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, 
      ),
    );
  }
}

父文件

// 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),
          ],
        )
      ),
    );
  }
}
z31licg0

z31licg01#

Function更改为

void Function functionName(){}

VoidCallback functionName(){}
cwdobuhd

cwdobuhd2#

同样的问题,我已经面临更新后,这是工作

import 'package:flutter/material.dart';
 
class Answer extends StatelessWidget {
 
  final VoidCallback clickFunction;
  const Answer(this.clickFunction,{Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        padding: const EdgeInsets.all(5),
        child: RaisedButton(
          padding: const EdgeInsets.all(10),
          color: Colors.blue,
          onPressed: clickFunction,
          child: const Text("This is texxt"),
        ));
  }
}
k10s72fa

k10s72fa3#

这对我很有效

final void Function()? FunctionName;

相关问题