我开始研究移动开发,有很多疑问和问题.我有课要上.我正在传递一个字段值"Score",但得到了一个错误.帮我理解一下.谢谢. 我的错误:类型‘()=>Null’不是类型转换中类型‘(Int)=>void’的子类型

这是主要的

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static const _questions = [
    {
      'questionText': 'What\'s your favorite color?',
      'answers': [
        {'text': 'Red', 'score': 10},
        {'text': 'Blue', 'score': 7},
        {'text': 'Green', 'score': 5},
        {'text': 'Yellow', 'score': 2},
      ],
    },
    {
      'questionText': 'What do you do?',
      'answers': [
        {'text': 'Eat', 'score': 9},
        {'text': 'Sleep', 'score': 10},
        {'text': 'Drink water', 'score': 4},
        {'text': 'Run', 'score': 3},
      ],
    },
    {
      'questionText': 'Do you have chairs?',
      'answers': [
        {'text': 'Yes', 'score': 10},
        {'text': 'No', 'score': 1},
        {'text': 'A lot', 'score': 3},
        {'text': 'I don\'t know', 'score': 7},
      ],
    },
    {
      'questionText': 'Would you like some red wine?',
      'answers': [
        {'text': 'Yes', 'score': 1},
        {'text': 'No', 'score': 9},
        {'text': 'I don\'t drink alcohol', 'score': 10},
        {'text': 'No, I would like soda', 'score': 7},
      ],
    },
  ];

  var _questionIndex = 0;
  var _totalScore = 0;

  void _answerQuiz(int score) {
    _totalScore += score;
    setState(() {
      _questionIndex++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'QuiZ',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Quiz'),
        ),
        body: _questionIndex < _questions.length
            ? Quiz(
                questions: _questions,
                questionIndex: _questionIndex,
                answerQuestion: _answerQuiz,
              )
            : Result(_totalScore),
      ),
    );
  }
}

这是班级测验

class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final void Function(int) answerQuestion;
  // final VoidCallback answerQuestion;

  const Quiz({
    required this.questions,
    required this.questionIndex,
    required this.answerQuestion,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          Question(questions[questionIndex]['questionText'] as String),
          ...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
              .map((answer) {
            return Answer(
              answer['text'] as String,
                () {
                  answerQuestion(answer['score'] as int);
                } as void Function(int p1),
            );
          }).toList(),
        ],
      ),
    );
  }
}

这是班级的答案

class Answer extends StatelessWidget {
  final String answerText;
  final void Function(int) selectHandler;
  // final VoidCallback selectHandler;

  const Answer(this.answerText, this.selectHandler, {super.key});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: const ButtonStyle(
        backgroundColor: MaterialStatePropertyAll(Colors.cyan),
        foregroundColor: MaterialStatePropertyAll(Colors.blueAccent),
      ),
      onPressed: () => selectHandler,
      child: Text(answerText),
    );
  }
}

这节课的成绩

class Result extends StatelessWidget {
  final int resultScore;
  const Result(this.resultScore, {super.key});

  String get resultPhrase {
    var resultText = 'You did it';
    if (resultScore <= 8) {
      resultText = 'You are awesome and innocent';
    } else if (resultScore <= 12) {
      resultText = 'Pretty likeable';
    } else if (resultScore <= 16) {
      resultText = 'You are ... strange?!';
    } else {
      resultText = 'You are so bad!!!';
    }

    return resultText;
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(resultPhrase),
    );
  }
}

我希望得到的值是"分数"

推荐答案

问题是唯一的答题课

ElevatedButton的onpressed参数未接收要传递的函数类型.

通过这样做来修复它: 已将onPressed行更正为onPressed: selectHandler行.

class Answer extends StatelessWidget {
  final String answerText;
  final void Function() selectHandler;
  // final VoidCallback selectHandler;

  const Answer(this.answerText, this.selectHandler, {super.key});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: const ButtonStyle(
        backgroundColor: MaterialStatePropertyAll(Colors.cyan),
        foregroundColor: MaterialStatePropertyAll(Colors.blueAccent),
      ),
      onPressed: selectHandler, //call the function properly
      child: Text(answerText),
    );
  }
}

Flutter相关问答推荐

为什么我需要等待重新访问Firestore数据库,即使它已经做了之前?

CLI数据库连接后将SHA-1密钥添加到Firebase项目

在 flutter 吧蜂巢中拯救主题

在使用FutureProvider时,我想显示用于加载的指示器,但无法自定义大小

Flutter在CustomPainter的右上角和左上角添加了2条曲线

如何使用providerContainer监听/写入FutureProvider?

Flutter http 请求获取 null

如何在 VS Code 中启用 Flutter 运行/调试工具栏?

即使小部件比Flutter 中的屏幕更宽,也始终显示滚动条

如果有空间则居中CustomScrollView

「Flutter」错误:没有名为'kind'的命名参数

FutureProvider 不返回数据给 UI

从所有设备注销,因为用户帐户已从 firebase flutter 中删除

升级到 Flutter 3.10 后,Flutter 键盘填充不起作用. Flutter 3.10 如何防止 BottomSheet 被键盘覆盖?

Paypal 支付网关添加带有 magento 2 网络详细信息用户名、密码、签名 Magento 2 的 flutter 应用程序?

如何删除或隐藏覆盖

Flutter 分析发现 Gitlab CI/CD 管道中的问题,但它在本地没有

容器在发布模式下显示灰色框(抖动)

如何获得Flutter 的时差?

如何从 Flutter 中的列表中提取 JSON?