Dart error: Not a valid override, don't override fields

Dart error: Not a valid override, don't override fields

在我的 Flutter 应用程序中,我有很多不同的控制器在做类似或相同的事情。所以我想我可以创建一个主控制器并将所有其他控制器扩展到这个控制器,这将为我节省大量重复代码。像这样:

abstract class Vehicle {
  final int seats;
  const Vehicle({required this.seats});
}

class Car extends Vehicle {
  final Color color;
  Car({required int seats, required this.color}) : super(seats: seats);
}

class Bus extends Vehicle {
  Bus({required int seats}) : super(seats: seats);
}

/*-------*/

abstract class VehicleController extends GetxController {
  Rx<Vehicle> vehicle = Bus(seats: 0).obs;

  void loadVehicle(Vehicle newVehicle) {}

  void printSeats() => print(vehicle.value.seats.toString());
}

class CarController extends VehicleController {
  @override
  Rx<Car> vehicle = Car(seats: 4, color: Colors.red).obs; // Error: not a valid override, Error: don't override fields.

  @override
  void loadVehicle(Car newVehicle) { // Error: not a valid override
    print(newVehicle.color);
  }

  void doSomeThingThatVehicleControllerCantDo() {
    print(vehicle.value.color);
  }
}

class BusController extends VehicleController {
  @override
  Rx<Bus> vehicle = Bus(seats: 50).obs; // Error: not a valid override, Error: don't override fields.
}

/*-------*/

void main() {
  CarController().printSeats();
  BusController().printSeats();
  CarController().doSomeThingThatVehicleControllerCantDo();
}

但是 Dart 不允许我覆盖字段并且不允许我用不同的对象覆盖 - 即使它扩展了它想要的对象。 有没有办法做到这一点? (对不起,我不是一个有经验的程序员)

首先,使用构造函数初始化字段而不是覆盖。 其次,使用像下面这样的通用模板来简化代码。

import 'package:flutter/material.dart';
import 'package:get/get.dart';

abstract class Vehicle {
  final int seats;

  const Vehicle({required this.seats});
}

class Car extends Vehicle {
  final Color color;

  Car({required int seats, required this.color}) : super(seats: seats);
}

class Bus extends Vehicle {
  Bus({required int seats}) : super(seats: seats);
}

/*-------*/

abstract class VehicleController<T extends Vehicle> extends GetxController {
  Rx<Vehicle> _vehicle;

  Rx<T> get vehicle => _vehicle as Rx<T>;

  VehicleController({Rx<Vehicle>? vehicle}) : _vehicle = vehicle ?? Bus(seats: 0).obs;

  void loadVehicle(Vehicle newVehicle) {}

  void printSeats() => print(vehicle.value.seats.toString());
}

class CarController extends VehicleController<Car> {
  CarController() : super(vehicle: Car(seats: 4, color: Colors.red).obs);
  
  @override
  void loadVehicle(Vehicle newVehicle) {
    if (newVehicle is Car) {
      print(newVehicle.color);
    }
  }

  void doSomeThingThatVehicleControllerCantDo() {
    print(vehicle.value.color);
  }
}

class BusController extends VehicleController<Bus> {
  BusController() : super(vehicle: Bus(seats: 50).obs);
}

/*-------*/

void main() {
  CarController().printSeats();
  BusController().printSeats();
  CarController().doSomeThingThatVehicleControllerCantDo();
}