Home > Mobile >  Dart Error: Can't access 'this' in a field initializer
Dart Error: Can't access 'this' in a field initializer

Time:07-20

I am having some trouble with class inheritance in dart and I'm not sure what I'm doing wrong. I am inheriting a class with the extends keyword, but when I try to make the constructor for that class I am getting some errors.

Here is my code:

@JsonSerializable(constructor: '_', fieldRename: FieldRename.snake)
class ParentClass {
  final DateTime time;
  final String bar;

  ParentClass ._(
      {required this.time,
      required this.bar});

  factory ParentClass.fromRecord(MyRecord record, String bar) {
    return ParentClass._(
        time: record.time.toUtc(),
        bar: bar);
  }

  factory ParentClass.fromJson(Map<String, dynamic> json) =>
      _$ParentClassFromJson(json);

  Map<String, dynamic> toJson() => _$ParentClassToJson(this);
}

@JsonSerializable(constructor: '_', fieldRename: FieldRename.snake)
class ChildClass extends ParentClass {
  final DateTime time;
  final String bar;
  final int id;

  ChildClass._(
      {required this.time,
      required this.bar,
      required this.id});

  factory ChildClass.fromRecord(MyRecord2 record, String bar) {
    return TimingEvent._(
        id: record.id,
        time: record.time.toUtc(),
        bar: bar);
  }

  factory ChildClass.fromJson(Map<String, dynamic> json) =>
      _$ChildClassFromJson(json);

  Map<String, dynamic> toJson() => _$ChildClassToJson(this);
}

When I run this, I get the error: Error: The superclass, 'ParentClass', has no unnamed constructor that takes no arguments. This error is being encountered at the line where the ChildClass is constructed: ChildClass._(

I then try to resolve that error by specifying the constructor for the superclass within the child class. I do this by changing the code from this:

   ChildClass._(
      {required this.time,
      required this.bar,
      required this.id});

to this:

   ChildClass._(
      {required this.id})
      : super._(time: this.time, bar: this.bar);

However, after making this change, I then get another error message: Error: Can't access 'this' in a field initializer. How am I supposed to pass the values through to the superclass constructor without using this?

CodePudding user response:

If you are using dart 2.17 or higher, the correct syntax for the constructor should be:

  ChildClass._({required super.time, required super.bar, required this.id})
      : super._();

Or if you using a version of dart lower than 2.17:

  ChildClass._({required DateTime time, required String bar, required this.id})
      : super._(time: time, bar: bar);

Note that you should also remove time and bar as properties from the ChildClass. These properties are already defined in the ParentClass, defining them again in ChildClass is redundant.

  • Related