Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make super constructor required in dart

Tags:

flutter

dart

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{}
like image 382
forJ Avatar asked Oct 20 '25 13:10

forJ


2 Answers

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.
like image 128
jamesdlin Avatar answered Oct 23 '25 04:10

jamesdlin


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);
}
like image 42
Federick Jonathan Avatar answered Oct 23 '25 04:10

Federick Jonathan