异步加载问题时,如何修复Flutter中的LateInitializationError?

ff29svar  于 2023-06-07  发布在  Flutter
关注(0)|答案(1)|浏览(227)

我在Flutter中有一个LateInitializationError,我不知道如何修复它。我正在制作一个测验应用程序,并从API请求问题。错误只显示了半秒钟,然后问题加载。我试着延迟之后的功能,但没有帮助。
我得到的具体错误是:

The following LateError was thrown building Quiz(dirty, state: _QuizState#74551):
LateInitializationError: Field 'currentQuestion' has not been initialized.

When the exception was thrown, this was the stack: 
#0      _QuizState.currentQuestion (package:demoapp/main.dart)
#1      _QuizState.build (package:demoapp/main.dart:267:21)

验证码:

class Quiz extends StatefulWidget {
  @override
  State<Quiz> createState() => _QuizState();
}

class _QuizState extends State<Quiz> {
  late Questions currentQuestion;
  late List<String> answers;
  List<bool?> answerValidation = [null, null, null, null];

  @override
  void initState() {
    asyncQuestion();
    super.initState();
  }

  void asyncQuestion() async{
    Questions currentQuestion1 = await loadQuestion();
    setState((){
      currentQuestion = currentQuestion1;
      answers = getRandomQuestionList(currentQuestion.wrongAnswers, currentQuestion.correctAnswer);
    });
  }

  validateAndShowQuestion(int userAnswerIndex) {
    int correctIndex = getCorrectAnswerIndex(currentQuestion.wrongAnswers, currentQuestion.correctAnswer);

    setState(() {
      if(userAnswerIndex == correctIndex) {
        answerValidation[correctIndex] = true;
        AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();
        audioPlayer.open(
          Audio(
            'assets/correct-6033.mp3',
          ),
        );
      }
      else {
        answerValidation[userAnswerIndex] = false;
        AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();
        audioPlayer.open(
          Audio(
            'assets/wrong-47985.mp3',
          ),
        );
      }

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),

      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Spacer(),
              Text((currentQuestion.question), style: TextStyle(color: Colors.black, fontSize: 22, fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              const Spacer(),
              GestureDetector(child: answerCard((answers[0]), context, answerValidation[0]),
                onTap: () {
                  validateAndShowQuestion(0);
                },),
              GestureDetector(child: answerCard((answers[1]), context, answerValidation[1]),
                onTap: () {
                  validateAndShowQuestion(1);
                },),
              GestureDetector(child: answerCard((answers[2]), context, answerValidation[2]),
                onTap: () {
                  validateAndShowQuestion(2);
                },),
              GestureDetector(child: answerCard((answers[3]), context, answerValidation[3]),
                onTap: () {
                  validateAndShowQuestion(3);
                },),
              const Spacer(),
            ]
          ),
        ),
      )
    );
  }
}

我真的很感激任何帮助。
我试着延迟下一个功能,但没有用。我还尝试将变量更改为可空变量。该方法的问题是,问题和答案被错误的值初始化。

ssm49v7z

ssm49v7z1#

问题出在以下部分:Text((currentQuestion.question)。这段代码位于build方法中,该方法首先运行。但是,此时您还没有为currentQuestion变量赋值。要解决此问题,请使用加载程序等待数据加载。通过这样做,你将有效地解决这个问题。

相关问题