satchel
satchel

Reputation: 547

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

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~!

Upvotes: 0

Views: 70

Answers (2)

Kasymbek R. Tashbaev
Kasymbek R. Tashbaev

Reputation: 1473

if (chatDoc.users!.contains(chatUser)) will throw an error, if the users property 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) {}

Upvotes: 2

Hippo Fish
Hippo Fish

Reputation: 708

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

Upvotes: 0

Related Questions