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.
https://stackoverflow.com/questions/66468181/how-to-use-the-null-assertion-operator-with-instance-fields March 04, 2021 at 11:33AM
没有评论:
发表评论