Search code examples
dartinheritancedart-null-safety

How to override nullable field with non-nullable one dart


I have a class with a nullable property. I would like to make a superclass that overrides that property with a non nullable one

so

class Example {
String? name;
}

class NamedExample extends Example {
@override
String name;

}

Is there some way to do that? if not how is this goal conventionally accomplished.

I basically want two identical classes except one of them always has a property while it is optional in another.


Solution

  • This is a place for the covariant keyword. Normally it does not make sense to override a parameter's type with its subtype and it is invalid to do so. This keyword tells the analyzer this is intentional. It can be added in either the super or subclass.

    Subclass:

    class Example {
      String? name;
    }
    
    class NamedExample extends Example {
      @override
      covariant String name;
      
      NamedExample(this.name);
    }
    

    Superclass:

    class Example {
      covariant String? name;
    }
    
    class NamedExample extends Example {
      @override
      String name;
      
      NamedExample(this.name);
    }