简体   繁体   中英

Dart Initialise Super Constructor in Factory Named Constructor

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.

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
    );
  }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM