Search code examples
dartconditional-statementsnullable

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


Solution

  • 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) {}