Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to super() call with complex arguments in Dart?

Tags:

dart

Up to what I researched, in Dart you gotta call super outside the function body of the constructor.

Suppose this situation:

/// Unmodifiable given class
class Figure{
  final int sides;
  const Figure(this.sides);
}

/// Own class
class Shape extends Figure{
  Shape(Form form){
    if(form is Square) super(4);
    else if(form is Triangle) super(3);
  }
}

That throws analysis errors (the superclass doesn't have 0 parameters constructor & the expression super(3) doesn't evaluate to a function, so it can't be invoked). How could I achieve the desidered functionality of the example?

like image 394
Nico Rodsevich Avatar asked Jun 04 '18 16:06

Nico Rodsevich


People also ask

How do you use super in darts?

Super Keyword in Dart: In Dart, super keyword is used to refer immediate parent class object. It is used to call properties and methods of the superclass. It does not call the method, whereas when we create an instance of subclass than that of the parent class is created implicitly so super keyword calls that instance.

What is _() in Dart?

_(); is a named constructor (another examples might be the copy constructor on some objects in the Flutter framework: ThemeData. copy(...); ). In dart, if the leading character is an underscore, then the function/constructor is private to the library.

How do you call a parent class constructor in darts?

Child_class_constructor() :super() { ... } Implicit super: In this case, the parent class is called implicitly, when there is object creation of child class. Here we don't make use of the super constructor but when the child class constructor is invoked then it calls default parent class constructor.


1 Answers

In Dart for calling the super constructor the initializer list is used.

class Shape extends Figure{
  Shape(Form form) : super(form is Square ? 4 : form is Triangle ? 3 : null);
}

if you need to execute statements you can add a factory constructor that forwards to a (private) regular constructor like

class Shape extends Figure{

  factory Shape(Form form) {
    if (form is Square) return new Shape._(4);
    else if(form is Triangle) return new Shape._(3);
  }
  Shape._(int sides) : super(sides)
}
like image 138
Günter Zöchbauer Avatar answered Jan 03 '23 17:01

Günter Zöchbauer