简体   繁体   中英

How can I solve "NoSuchMethodError: The method "[]" was called on null

gamelist is a String List of document names in the collection. The questionMap value is an array named "text" field obtained from the firestore document using the gamelist value as key. I would like to update the questionMap when I press the pass button, When I press the pass button, I see that the questionMap is indeed updated when I print in this code, but the screen is not redrawn and I get the error as shown in the title. It is a dirty code, but I would like to know how to solve it.

This is my code:

class PlayPage extends StatefulWidget {
  List gameList;
  Map questionMap;
  String category;
  int myScore;

  PlayPage({
    required this.gameList,
    required this.category,
    required this.myScore,
    required this.questionMap,
  });

  @override
  State<PlayPage> createState() => _PlayPageState();
}

class _PlayPageState extends State<PlayPage> {
  int quizNumber = 0;
  int listNumber = 0;
  var db = FirebaseFirestore.instance;

  void changeQuiz() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Stack(
        children: [
          Card(
            child: SizedBox(
              height: double.infinity,
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.only(
                      top: 20, bottom: 200, left: 20, right: 20),
                  child: Text(
                    widget.questionMap[widget.gameList[listNumber]][quizNumber],
                    style: const TextStyle(fontSize: 20),
                  ),
                ),
              ),
            ),
          ),
          Positioned(
            right: 10,
            bottom: 30,
            child: Column(
              children: [
                ElevatedButton(
                  child: const Text(
                    "Pass",
                    style: TextStyle(fontSize: 30),
                  ),
                  onPressed: () {
                    listNumber += 1;
                    quizNumber = 0;
                    setState(
                      () {
                        var docRef = db
                            .collection(widget.category)
                            .doc(widget.gameList[listNumber]);
                        docRef.get().then(
                          (DocumentSnapshot doc) {
                            var data = doc.data() as Map<String, dynamic>;
                            List questions = selectQuiz(
                              data["text"],
                            );
                            widget.questionMap = {
                              widget.gameList[listNumber]: questions
                            };
                            print(widget.questionMap);
                          },
                        );
                      },
                    );
                  },
                ),
                const SizedBox(height: 30),
                SizedBox(
                  width: 70,
                  height: 70,
                  child: FloatingActionButton(
                    backgroundColor:
                        (quizNumber < 9) ? Colors.teal : Colors.grey,
                    child: const Icon(
                      Icons.arrow_forward,
                      size: 35,
                    ),
                    onPressed: () {
                      if (quizNumber < 9) {
                        setState(
                          () {
                            quizNumber += 1;
                          },
                        );
                      }
                    },
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

Make sure that the object you are trying to access is not null before you try to access it. The error message NoSuchMethodError: The method '[]' was called on null is telling you that you've called the index ( [] ) operator on null.

This error occurs when a method or property has been called but it does not exist in the current context due to some type mismatch or incorrect data format being passed into it as an argument. Examine the stack trace and look at the line number where the failure occurred.

As mentioned here

For example, let's imagine you see:

 Unhandled exception: NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: []("data") #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5) #1 main (file:///Users/cbracken/foo.dart:3:23)...

The stack trace above is telling you that the call on the null object was in main on line 3 of file foo.dart. Further, it's telling you that the [] operator was called with the parameter 'data' . If I look at that line in my code and it says var foo = json['localteam']['data'] , then I would deduce that json['localteam'] is returning null.

It can be solved by identifying the exact location where it occurred followed by fixing typos/mistakes related argument passing along with ensuring proper variable declarations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM