0
votes

I'm having trouble understanding how to type promote an object's field if it is nullable. Let's say I had the following Comment class and tried to access its one nullable field:

class Comment {
  final String? text;
  Comment(this.text); 
}

void main() {
  final comment = Comment("comment");
  
  if (comment.text!= null) {
    String text = comment!.text;
  }
}

The Dart compiler would give me an error for trying to assign a nullable variable to a non-nullable variable. From what I've gathered from looking into this topic, it's impossible to have type promotion with instance variables because instance variables can be modified which can then break the sound null-safety. I've seen the Null assertion operator (!.) being used in these circumstances, however it doesn't seem to work with fields, only with methods.

With dart null-safety, how should I go about assigning a nullable field such as String? to a non-nullable variable (String). To the same effect, how should I go about passing a nullable field to a function that requires a non-null argument.

1
You're putting the ! in the wrong place. comment is known to not be null; its member is what's not guaranteed to be non-null, so you need to do String text = comment.text!;. - jamesdlin
This was exactly the answer I was looking for. Thank you! - Kalapapa

1 Answers

1
votes

You can fix it in different ways:

  1. Use local variable (recommended)

    final local = comment.text; // <-- Local variable
    if (local != null) {
      String text = local; 
    }
    
  2. Use ?. and provide a default value

    String text = comment?.text ?? 'Default value';
    
  3. Use Bang operator !

    if (comment.text != null) {
      String text = comment.text!; // <-- Bang operator
    }
    

Note: Bang operator can result in a runtime error if the text was null.