Home > Enterprise >  NoSuchMethodError was thrown while running. The method '[]' was called on null. Receiver:
NoSuchMethodError was thrown while running. The method '[]' was called on null. Receiver:

Time:11-25

I'm developing a mobile application using Flutter-SQLite-Dart. This app is basically a quiz application. The app runs fine but initially when running a particular error pops and then resumes as coded.

While calling question index from model the following error occurs and then the application works normally.

NoSuchMethodError was thrown while initializing the build

Only the first time when running this error appears. According to my knowledge this error occurs because this state is called before initializing it, but I have properly initialized it in initState() function.

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building:
The method '[]' was called on null.
Receiver: null
Tried calling: [](0)

When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:68:5)
#1      _QuizPageState.buildNotes.<anonymous closure> (package:loginform_validation_demo/QuizApp/screens/quiz/quiz_screen_stateful.dart:97:28)
#2      SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:456:22)
#3      SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1214:28)
#4      SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1227:55)
#5      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2531:19)
#6      SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1220:12)
#7      RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:349:23)
#8      RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1968:59)
#9      PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:916:15)
#10     RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1968:14)
#11     RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:338:5)
#12     RenderSliverMultiBoxAdaptor.addInitialChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:422:5)
#13     RenderSliverFixedExtentBoxAdaptor.performLayout (package:flutter/src/rendering/sliver_fixed_extent_list.dart:205:12)
#14     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#15     RenderSliverEdgeInsetsPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:137:12)
#16     _RenderSliverFractionalPadding.performLayout (package:flutter/src/widgets/sliver_fill.dart:167:11)
#17     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#18     RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:510:13)
#19     RenderViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1580:12)
#20     RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1489:20)
#21     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#22     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#23     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#24     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#25     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#26     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#27     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#28     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#29     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#30     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#31     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#32     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#33     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#34     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#35     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#36     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#37     RenderCustomPaint.performLayout (package:flutter/src/rendering/custom_paint.dart:545:11)
#38     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#39     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#40     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#41     RenderPositionedBox.performLayout (package:flutter/src/rendering/shifted_box.dart:437:14)
#42     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#43     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:171:12)
#44     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:983:7)
#45     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:240:7)
#46     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:404:14)
#47     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#48     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#49     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#50     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#51     _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1376:11)
#52     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#53     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#54     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#55     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#56     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#57     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#58     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#59     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#60     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#61     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#62     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#63     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#64     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#65     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#66     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#67     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#68     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#69     RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:3408:14)
#70     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#71     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:116:14)
#72     RenderObject.layout (package:flutter/src/rendering/object.dart:1858:7)
#73     _RenderTheatre.performLayout (package:flutter/src/widgets/overlay.dart:751:15)
#74     RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1713:7)
#75     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:885:18)
#76     RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:453:19)
#77     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:13)
#78     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:319:5)
#79     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1145:15)
#80     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9)
#81     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:996:5)
#85     _invoke (dart:ui/hooks.dart:166:10)
#86     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:270:5)
#87     _drawFrame (dart:ui/hooks.dart:129:31)
(elided 3 frames from dart:async)
====================================================================================================
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The Quiz screen is given below, Error occurring place is in itemBuilder under buildNotes() widget,

itemBuilder: (context, index) {

      //Error occurring place
      note = question[index];
      .
      .
      }

Only the first time when compiled this error is printed.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loginform_validation_demo/QuizApp/controllers/question_controller_copy.dart';
import 'package:loginform_validation_demo/QuizApp/database/quiz_database.dart';
import 'package:loginform_validation_demo/QuizApp/models/Album.dart';

class QuizPage extends StatefulWidget {
  final BlazorQuiz quiz;

  const QuizPage({Key key, this.quiz}) : super(key: key);

  @override
  _QuizPageState createState() => _QuizPageState();
}

class _QuizPageState extends State<QuizPage> {
  List<BlazorQuiz> question;
  List<BlazorQuiz> answer;
  bool isLoading = false;
  String title;
  BlazorQuiz note;

  @override
  void initState() {
    super.initState();
    note = question as BlazorQuiz;

    this.title = widget.quiz?.Question ?? 'Question';
    refreshNotesBlazor();
  }

  @override
  void dispose() {
    debugPrint(" QuizCheckModel dispose called ");
    QuizDatabase.instance.close();
    super.dispose();
  }
 Future refreshNotesBlazor() async {
 setState(() => isLoading = true);

 this.question = (await QuizDatabase.instance.readAllNotesBlazor());
 this.answer = (await QuizDatabase.instance.readAllNotesBlazorAnswer());
 setState(() => isLoading = false);
 debugPrint(
    " Blazor QuizCheckModel refreshNotes Question : ${this.question}");
 debugPrint(" Blazor QuizCheckModel refreshNotes Answer : 
 ${this.answer}");
 }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text(
            'Quiz App',
            style: TextStyle(fontSize: 24),
          ),
          automaticallyImplyLeading: false,
          actions: [Icon(Icons.search), SizedBox(width: 12)],
        ),

        body: Center(child: buildNotes()),
      );

  QuestionControllerCopy _questionController =
      Get.put(QuestionControllerCopy());

   Widget buildNotes() => PageView.builder(
        physics: NeverScrollableScrollPhysics(),
        controller: _questionController.pageController,
    itemCount: 18,

    itemBuilder: (context, index) {
          //Error occurring place
          note = question[index];
          debugPrint('QuizScreenStateful : $question');
          debugPrint('QuizScreenStateful index : $index');
          debugPrint('QuizScreenStateful question-index : ${question[index]}');

          return SafeArea(
            child: Column(
              children: [

                if (question[index].QnType == 'Statement') ...[

                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetStart(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ] else if (question[index].QnType == 'Radio') ...[
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetRadio(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ] else if (question[index].QnType == 'Check') ...[
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetCheck(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ] else if (question[index].QnType == 'Drop') ...[
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetDropdown(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ]
                else if (question[index].QnType == 'EditText') ...[
                    Expanded(
                      child: SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        child: QuestionCardWidgetEditText(
                            note: note,
                            index: index,
                            questionLength: question.length),
                      ),
                    ),
                  ]
                else if (question[index].QnType == 'End') ...[
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetEnd(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ] else ...[
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidget(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ]
              ],
            ),
          );
        },
      );
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

note = question[index];

Your question variable is null. Why? Well, I cannot see a line of code setting it to something else, so it still is null.

So two remarks to fix this:

  • use a current version of Flutter. The version you use is outdated. The current version would not allow this without warning you about your mistake.

  • Make sure your question variable is filled with something that is not null.

CodePudding user response:

just do changes to your Future functions like this

  Future refreshNotesBlazor() async {
    setState(() => isLoading = true);
    final question = (await QuizDatabase.instance.readAllNotesBlazor());
    setState(() => isLoading = false);
    debugPrint(
        " Blazor QuizCheckModel refreshNotes Question : ${this.question}");
    return question;
    }
    
  Future refreshNotesBlazor2() async {
    setState(() => isLoading = true);
    final answer = (await QuizDatabase.instance.readAllNotesBlazor());
    setState(() => isLoading = false);
    debugPrint(" Blazor QuizCheckModel refreshNotes Answer : 
        ${this.answer}");
    return answer;
    }

and use this for your screen

Widget buildNotes() => FutureBuilder(
      future: refreshNotesBlazor(),
      builder: (context, snapshot) => snapshot.hasData ? PageView.builder(
        physics: NeverScrollableScrollPhysics(),
        controller: _questionController.pageController,
        itemCount: 18,

        itemBuilder: (context, index) {
          //Error occurring place
          note = question[index];
          debugPrint('QuizScreenStateful : $question');
          debugPrint('QuizScreenStateful index : $index');
          debugPrint('QuizScreenStateful question-index : ${question[index]}');

          return SafeArea(
            child: Column(
              children: [

                if (question[index].QnType == 'Statement') ...[

                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetStart(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ] else if (question[index].QnType == 'Radio') ...[
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetRadio(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ] else if (question[index].QnType == 'Check') ...[
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetCheck(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ] else if (question[index].QnType == 'Drop') ...[
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: QuestionCardWidgetDropdown(
                          note: note,
                          index: index,
                          questionLength: question.length),
                    ),
                  ),
                ]
                else if (question[index].QnType == 'EditText') ...[
                    Expanded(
                      child: SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        child: QuestionCardWidgetEditText(
                            note: note,
                            index: index,
                            questionLength: question.length),
                      ),
                    ),
                  ]
                  else if (question[index].QnType == 'End') ...[
                      Expanded(
                        child: SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          child: QuestionCardWidgetEnd(
                              note: note,
                              index: index,
                              questionLength: question.length),
                        ),
                      ),
                    ] else ...[
                      Expanded(
                        child: SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          child: QuestionCardWidget(
                              note: note,
                              index: index,
                              questionLength: question.length),
                        ),
                      ),
                    ]
              ],
            ),
          );
        },
      ) : Center(child: CircularProgressIndicator(),));
  • Related