How to make super constructor required in dart

Viewed 2485

I would like the IDE to inform me that I need to construct super constructor in inherited widget's constructor. Say for example if I have abstract class like below

abstract class BaseClass {
  final String name;

  BaseClass({
    @required String name,
  }) : this.name = name;
}

I want the child class to know that I need to implement the super constructor. The below code throws at runtime but how do I make sure that it throws in build time or IDE lets me know before build?

class ChildClass extends BaseClass{}
3 Answers

Step 1 :

abstract class BaseClass {
  final String name;

  BaseClass(
    String name,
  ) : this.name = name;
}

class ChildClass extends BaseClass{
  ChildClass() {}
}

You will get a warning from IDE :

The superclass 'BaseClass' doesn't have a zero argument constructor.

This means that you need to call the superclass's constructor in the ChildClass's constructor.

Step 2 :

class ChildClass extends BaseClass{
  ChildClass() : super('Shubham');
  
  get getName => name;
}

Now we can test it making an instance of ChildClass.

void main() {
 var child =  ChildClass();
  print('Name : ${child.getName}');
}

Output :

Shubham

As stated in the doc Dart lang tour

Constructors aren’t inherited

Subclasses don’t inherit constructors from their superclass. A subclass that declares no constructors has only the default (no argument, no name) constructor.

Therefore you have to call the super constructor in order to get the build time warning.

class ChildClass extends BaseClass{
  ChildClass() : super(); // This will give you 'The parameter 'name' is required.'
}

But to get the warning when you try to instantiate it, you will need to add another required annotation anyway.

class ChildClass extends BaseClass{
  ChildClass({@required name}) : super(name: name);
}

If a derived class neglects to explicitly invoke a base class constructor, it implicitly invokes the base class's default (unnamed) constructor with zero arguments. You therefore have several options to get a build-time warning:

  • Do not give the base class an unnamed constructor. Make all base class constructors named.
  • Make the unnamed base class constructor use one or more required positional parameters.
  • Make the unnamed base class constructor use one or more required named parameters. This requires enabling Dart's null safety features and using the new required keyword instead of package:meta's @required annotation.
Related