0

i am developing a flutter quiz. Error:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════ The following NoSuchMethodError was thrown building QuizPage (dirty, state: _QuizPageState # 307d6): The getter 'length' was called on null. Receiver: null Tried calling: length

error https://pastebin.com/8JCG7Ecj https://pastebin.com/s0kvXLr1

after a few seconds the application is executed

But I got an exception, where I know where the exception and what it means, but i do not have any clue how i could solve the problem. I hope some of you guys could help me.

Git: https://github.com/ivsongborges/app_g6pd.git

class QuizPage extends StatefulWidget {
  @override
  _QuizPageState createState() => _QuizPageState();
}

class _QuizPageState extends State<QuizPage> {
  final _controller = QuizController();
  List<Widget> _scoreKeeper = [];

  bool _loading = true;

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

  Future<void> _initialize() async {
    await _controller.initialize();

    setState(() {
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: Text('QUIZ G6PD ( ${_scoreKeeper.length}/${_controller.questionsNumber} )'),
        centerTitle: true,
        elevation: 0.0,
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 20.0),
          child: _buildQuiz(),
        ),
      ),
    );
  }

  _buildQuiz() {
    if (_loading) return CenteredCircularProgress();

    if (_controller.questionsNumber == 0)
      return CenteredMessage(
        'Sem questões',
        icon: Icons.warning,
      );

    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        _buildQuestion(_controller.getQuestion()),
        _buildAnswerButton(_controller.getAnswer1()),
        _buildAnswerButton(_controller.getAnswer2()),
        _buildScoreKeeper(),
      ],
    );
  }

  _buildQuestion(String question) {
    return Expanded(
      flex: 5,
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 16.0),
        child: Center(
          child: Text(
            question,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 25.0,
              color: Colors.black,
            ),
          ),
        ),
      ),
    );
  }

  _buildAnswerButton(String answer) {
    return Expanded(
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 8.0),
        child: GestureDetector(
          child: Container(
            padding: EdgeInsets.all(4.0),
            color: Colors.blue,
            child: Center(
              child: AutoSizeText(
                answer,
                maxLines: 2,
                minFontSize: 10.0,
                maxFontSize: 32.0,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                ),
              ),
            ),
          ),
          onTap: () {
            bool correct = _controller.correctAnswer(answer);

            ResultDialog.show(
              context,
              question: _controller.question,
              correct: correct,
              onNext: () {
                setState(() {
                  _scoreKeeper.add(
                    Icon(
                      correct ? Icons.check : Icons.close,
                      color: correct ? Colors.green : Colors.red,
                    ),
                  );

                  if (_scoreKeeper.length < _controller.questionsNumber) {
                    _controller.nextQuestion();
                  } else {
                    FinishDialog.show(
                        context,
                        hitNumber: _controller.hitNumber,
                        questionNumber:  _controller.questionsNumber
                    );
                  }
                });
              },
            );
          },
        ),
      ),
    );
  }

  _buildScoreKeeper() {
    return Expanded(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: _scoreKeeper,
      ),
    );
  }
}

1 Answers1

0

The error message in the link states something else:

    I/flutter (26474): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (26474): The following NoSuchMethodError was thrown building QuizPage(dirty, state: _QuizPageState#d376a):
I/flutter (26474): The getter 'length' was called on null.
I/flutter (26474): Receiver: null
I/flutter (26474): Tried calling: length
I/flutter (26474):
I/flutter (26474): The relevant error-causing widget was:
I/flutter (26474):   QuizPage file:///C:/Users/ivs_g/AndroidStudioProjects/dog/flutter_app/lib/pages/home.page.dart:26:43
I/flutter (26474):
I/flutter (26474): When the exception was thrown, this was the stack:
I/flutter (26474): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
I/flutter (26474): #1      QuizController.questionsNumber (package:flutter_app/controllers/quiz_controller.dart:13:44)
I/flutter (26474): #2      _QuizPageState.build (package:flutter_app/pages/quiz.page.dart:39:71)
I/flutter (26474): #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28)
I/flutter (26474): #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
I/flutter (26474): #5      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
I/flutter (26474): #6      Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
I/flutter (26474): #7      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)

It is clear that the last called method is QuizController.questionNumber hence, the problem is _contoller.questionNumber The problem is either that _controller hasn't been declared properly. It should be final QuizController _controller = QuizController(); or there is an error inside QuizController() For a more comprehensive answer check out What is a NoSuchMethod error and how do I fix it?

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
  • That is wrong. The error message does not talk about `_contoller.questionNumber`. Look at it, it very prominently says that `.length` was called on `null`, and that is the case for another variable, not the one you mentioned. That said, this is a common problem, please direct the people to the canonical answer that teaches them to solve it themselves, instead of answering the same question over and over and over again. Vote to close a duplicate, don't reinvent the wheel. – nvoigt Oct 07 '20 at 05:41
  • If you look at the link that he has shared it is clear that the length isn't actually the issue. As for guiding people to a canonical answer problem to this problem I was actually unaware of any canonical solution to this specific error. Apologizes for any inconvenience caused. @nvoigt Please have a look at the updated answer. – SARVESH TANDON Oct 07 '20 at 10:18
  • Well, I voted to close it as a duplicate, so you can see which answer I mean in the comment to the question. Please note that I wrote it and it's by no means the ultimate answer. If it can be improved, feel free to do so. But sending all the people to an answer that explains *how* they can solve their own problem is way more effective then giving each of them a single, manually found solution to their specific problem (which will teach them little and we will have them with a new question when it happens again). – nvoigt Oct 07 '20 at 10:22
  • You are absolutely right by the way, the error is in `int get questionsNumber => _questionBank.length ?? 0;` with `_questionBank` being null, it's in the git repository. – nvoigt Oct 07 '20 at 11:05
  • thanks. That's right. Resolved ```int get questionsNumber => _questionBank.length ?? 0; ```>>> ```int get questionsNumber => _questionBank?.length ?? 0;``` – Ivson Borges Oct 07 '20 at 11:47