Roufail
Roufail

Reputation: 573

how can i initialize super class variables in dart language?

Simply i have to classes child and parent class
i am new in dart language all i need to assign super class properties from child class

this is super class structure

class Trip{
  final int id;
  final String title;
  final double price;
  Trip({this.id,this.title,this.price});
}

and this is child class

class FullTrip extends Trip{
  final String data;
  FullTrip({this.data}) : super(id:id,title:title,price:price);
}

sure this not working at all
the question is : how can i initialize instance from FullTrip and pass variable for FullTrip and Trip(super class)
thanks in advance

Upvotes: 22

Views: 14266

Answers (3)

CopsOnRoad
CopsOnRoad

Reputation: 268544

User super-parameters, which were added in Dart 2.17. For example, say this is your class:

class Parent {
  Parent({
    int? i,
    bool b = false,
    required String s,
  });
}

Old way (boilerplate code)

Earlier you had to do something like this:

class Child extends Parent {
  Child({
    int? i,
    bool b = false,
    required String s,
  }) : super(
          i: i,
          b: b,
          s: s,
        );
}

New way (neat and clean)

But now you can get rid of those boilerplate code.

class Child extends Parent {
  Child({
    super.i, 
    super.b = false,
    required super.s,
  });
}

Upvotes: 13

Ivan Yoed
Ivan Yoed

Reputation: 4415

If you want to re-initialize in a subclass the not private variables of an extended or implemented upper class before compiling, simply use @override. Look at this example

(if you want to try the code, have in mind it supports null safety. If your test doesn't, simply delete the ? signs.)

class Go {
  String? name = "No name";
}

class Foo implements Go { //use either implements or extends
  @override
  String? name = "Foo";
}

class Doo extends Go { //use either implements or extends
  @override
  String? name = "Doo";
}

Use case example: In the code above, you can see that in our upper class we have this String name variable. Then in the subclasses we can simply override that variable. After that, in main we can now for example do something like iterating through a List<Go>, access what we wanted to and then trigger something, like printing the name:

void main() {
  
  List<Go> foos = [
    Go(),
    Foo(),
    Doo(),
  ];
  
  for(Go x in foos){
    print(x.name);
  }
}

Output:

No name
Foo
Doo

This works if you use either the extends or implements keywords.

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658263

You need to repeat the parameters in the subclass.

class FullTrip extends Trip{
  final String data;
  FullTrip({this.data, int id, String title, double price}) : super(id:id,title:title,price:price);
}

There are discussions about reducing such boilerplate for constructors, but nothing is decided yet as far as I know.

Upvotes: 46

Related Questions