Flutter:当我传递到2个无状态小部件时,无法执行带参数的void函数

f8rj6qna  于 2022-12-19  发布在  Flutter
关注(0)|答案(1)|浏览(107)

所以我遇到了这个问题。所以我有这个函数

int _questionIndex = 0;
  int _totalScore = 0;

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

我计划将此传递给2个小部件、测验和答案
测验

import 'package:app_1_starter/answer.dart';
import 'package:app_1_starter/question.dart';
import 'package:flutter/material.dart';

class Quiz extends StatelessWidget {
  final int index;
  final List<Map<String, Object>> questions;
  final Function pressHandler;

  const Quiz(
      {Key? key,
      required this.questions,
      required this.index,
      required this.pressHandler})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          Question(questions[index]['question'] as String),
          ...(questions[index]['answers'] as List<Map<String, Object>>)
              .map((answer) {
            return Answer(
              () => pressHandler(answer['score']),
              answer['text'] as String,
            );
          }).toList(),
        ],
      ),
    );
  }
}

测验是在只剩下几道题要回答的时候进行的。
这是答案小部件,它将提供答案布局

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final String buttonText;
  final Function pressHandler;

  const Answer(this.pressHandler, this.buttonText, {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.all(5),
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.blue),
        ),
        onPressed: pressHandler(),
        child: Text(
          buttonText,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }
}

我的SDK是环境:标准差k:“〉=2.17.6〈3.0.0”
错误一直在说

The following NoSuchMethodError was thrown building Answer(dirty):
Closure call with mismatched arguments: function '_MyAppState.build.<anonymous closure>'
Receiver: Closure: () => ({int score}) => void
Tried calling: _MyAppState.build.<anonymous closure>(30)
Found: _MyAppState.build.<anonymous closure>() => ({int score}) => void

我试着把答案的测验尚未,它不断给出相同的错误,如上述.
我不知道那是什么意思也不知道出了什么问题谢谢你能来
干杯

mspsb9vt

mspsb9vt1#

感谢@mmcdon20的建议,问题在main. dart上。
应该是这样的

Quiz(
 questions: _questions,
 index: _questionIndex,
 pressHandler: _answerQuestion,
)

相关问题