Home > database >  Method called on null error when it's not null
Method called on null error when it's not null

Time:11-03

Currently I'm building out a screen showing all of the chat messages I have with different users. I am using StreamBuilder, and for a couple of days it works perfectly fine and then all of a sudden it gives me the error:

The following NoSuchMethodError was thrown building StreamBuilder(dirty, state: _StreamBuilderBaseState<dynamic, AsyncSnapshot>#8720a): The method '[]' was called on null. Receiver: null Tried calling:

I've pasted a part of the code ending with the line that causes the error. It's telling me nextMessage is null but when I print nextMessage['users'], I get the ID of the users as expected...any thoughts on what's going on?

StreamBuilder<dynamic>(
                  stream: _myStream,
                  builder: (context, snapshot) {
                    final messageList = <BuildMessages>[];
                    if (snapshot.hasData == false ||
                        snapshot.data.snapshot.value == null) {
                      return Container();
                    } else {
                      if (snapshot.hasData &&
                          snapshot.data.snapshot.value != null) {
                        final users = Map<String, dynamic>.from(
                            snapshot.data.snapshot.value);
                        users.forEach((key, value) {
                          final nextMessage = Map<String, dynamic>.from(value);
                          late int index;
                          print(nextMessage['users'][0]);
                          if (myUser.userID == nextMessage['users'][0]) {
                            index = 1;
                          } else if (myUser.userID == nextMessage['users'][1]) {
                            index = 0;
                          }
                      

CodePudding user response:

users.forEach((key, value) {
                      final nextMessage = Map<String, dynamic>.from(value);
                      late int index;
                      print(nextMessage['users'][0]);
                      if (myUser.userID == nextMessage['users'][0]) {
                        index = 1;
                      } else if (myUser.userID == nextMessage['users'][1]) {
                        index = 0;
                      }
                  

well,seems like you're trying to get ['users'][0] like a list although you set nextMessage as a Map<String,dynamic>. I think that's the error. You said "I print nextMessage['users'], I get the ID", which makes me thinkg that nextMessage['users]' is only an ID, without others properties, so it doesn't make sense try to get [0] or [1]. Set some breakpoints in those lines to see what values you have and if it's compatible with your structure.

CodePudding user response:

change this

StreamBuilder<dynamic>

to this

StreamBuilder<QuerySnapshot<Map>>
  • Related