运行 时抛出 NoSuchMethodError。在 null 上调用了方法“[]”。接收者:无。尝试调用:[](0)。如何解决这个错误?

NoSuchMethodError was thrown while running. The method '[]' was called on null. Receiver: null. Tried calling: [](0). How to solve this error?

我正在使用 Flutter-SQLite-Dart 开发移动应用程序。这个应用程序基本上是一个测验应用程序。该应用程序运行良好,但最初 运行 弹出特定错误,然后按编码恢复。

从模型中调用问题索引时出现以下错误,然后应用程序正常运行。

只有第一次运行出现这个错误。据我所知,发生此错误是因为在初始化之前调用了此状态,但我已在 initState() 函数中对其进行了正确初始化。

======== 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)
====================================================================================================

测验屏幕如下所示, 错误发生的地方在buildNotes() widget下的itemBuilder中,

itemBuilder:(上下文,索引){

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

仅在第一次编译时打印此错误。

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),
                    ),
                  ),
                ]
              ],
            ),
          );
        },
      );
}

note = question[index];

您的 question 变量是 null。为什么?好吧,我看不到一行代码将其设置为其他内容,所以它仍然是 null.

所以有两条评论来解决这个问题:

  • 使用当前版本的 Flutter。您使用的版本已过时。当前版本不会在不警告您错误的情况下允许这样做。

  • 确保您的 question 变量填充了不为空的内容。

只需像这样更改您的 Future 函数:

  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;
    }

并将其用于您的屏幕:

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(),));