Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

dart - 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 {}?

question from:https://stackoverflow.com/questions/66069041/how-to-enforce-calling-abstract-class-constructor-when-using-non-positional-para

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...