user606521
user606521

Reputation: 15434

How to enforce calling abstract class constructor when using non positional parameters?

I have following code:

import 'package:meta/meta.dart';

class Dependency {}

abstract class A1 {
  final Dependency dependency;

  A1({ @required this.dependency }); // non positional parameter with @required (does not work)
}

abstract class A2 {
  final Dependency dependency;

  A2(this.dependency); // positional parameter (works causing analyzer error)
}

class B1 extends A1 {} // No error / warning
class B2 extends A2 {} // analyzer error: The superclass 'A2' doesn't have a zero argument constructor.

Is there any way to force analyzer to show error in case class B1 extends A1 {}?

Upvotes: 1

Views: 209

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17123

This can't be done with the stable version of dart at the moment. @required is just an annotation and not really a part of the language so the analyzer can't pick up on the problem you pose. However, with null-safety enabled in beta and higher channels, this is possible with the required keyword.

You can try this by enabling null-safety and changing @required to required.

You could try this easily in dartpad

or

switch to a beta or higher channel and change your dart sdk version constraints to have a minimum of 2.12.0-0.

sdk: ">=2.12.0-0 <3.0.0"

Upvotes: 1

Related Questions