Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Initialise Super Constructor in Factory Named Constructor

Tags:

flutter

dart

How do I initialise the variables of a super class in a named factory constructor? Here is my sample code:

class ClassA{
  final a;
  final b;

  ClassA({this.a, this.b});

}

class ClassB extends ClassA{
  final c;
  List <String> myList;

  ClassB({this.c,this.myList});


  factory ClassB.fromJson(json){
    var list = json["list"] as List;
    List<String> tempList = [];

    list.forEach((item)=>tempList.add(item));
    return ClassB(
      c: json["c"],
      myList: tempList
    );
  }


} 

I am not sure how or where exactly do i call the super constructor for Class A so that I can initialise its variables.

like image 882
spongyboss Avatar asked Dec 14 '25 05:12

spongyboss


1 Answers

Here is the way to call super:

class ClassA{
  final a;
  final b;

  ClassA({this.a, this.b});

}

class ClassB extends ClassA{
  final c;
  List <String> myList;

  ClassB({final a, final b, this.c,this.myList}) : super(a: a, b: b);

  factory ClassB.fromJson(json){
    var list = json["list"] as List;
    List<String> tempList = [];

    list.forEach((item)=>tempList.add(item));
    return ClassB(
      c: json["c"],
      myList: tempList
    );
  }
} 
like image 82
Thắng Mai Avatar answered Dec 16 '25 23:12

Thắng Mai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!