Home > database >  How do I check whether a conditional value in dart is null without using a condition?
How do I check whether a conditional value in dart is null without using a condition?

Time:01-03

I have the following code:

 if(chatDocsListwithAuthUser != null) {
    for(ChatsRecord chatDoc in chatDocsListwithAuthUser) {
      if(chatDoc.users.contains(chatUser)) {
        return chatDoc;
      }
    }
  }

I get an error that says (for example) chatDoc.users can't be used in the condition because it might be null.

But I cannot put before it if(chatDoc.users != null){...} because that is also a condition!

What is the standard way when going through loops and conditionals within those loops to deal with nullability in dart?

For now, I use the following: if (chatDoc.users!.contains(chatUser)) { but I don't know if this is right~!

CodePudding user response:

if (chatDoc.users!.contains(chatUser)) will throw an error, if the users parameter is null. Instead, make the boolean value nullable and, if it is null, set it to false using ?? operator. So we will have the following condition:

if (chatDoc.users?.contains(chatUser) ?? false) {}

CodePudding user response:

I think you can fix it with this:

if(chatDoc.users && chatDoc.users.contains(chatUser))

If the chatDoc.users is null, you will never get into chatDoc.users.contains

 if(chatDocsListwithAuthUser != null) {
    for(ChatsRecord chatDoc in chatDocsListwithAuthUser) {
      if(chatDoc.users && chatDoc.users.contains(chatUser)) {
        return chatDoc;
      }
    }
  }

CodePudding user response:

From what i see, The problem here is, you are saying the item has to be ChatsRecord. But in real, it can be null. So what you can do is make it ChatRecord?. Example ->

if(chatDocsListwithAuthUser != null) {
 for(ChatsRecord? chatDoc in chatDocsListwithAuthUser) {
   if(chatDoc.users.contains(chatUser)) {
    return chatDoc;
    }
  }
}

Later inside the loop you can check, if the item is null or not. Like ->

if(chatDocsListwithAuthUser != null) {
 for(ChatsRecord? chatDoc in chatDocsListwithAuthUser) {
   if(chatDoc != null && chatDoc.users.contains(chatUser)) {
       return chatDoc;
     }
  }
}
  • Related