'How can I use variables collected in a class when an object is instantiated within functions held in the class?

in Dart (version 2.15.1). I have made a class to define a car. I want to use some of the variables created when the 'car' object is instantiated in a class function, rather than have the user resupply the data a second time when calling the function. I cannot find a way to access the data I need in the function.

Here is my programme I have marked the lines that are not working:

// Programme to create a class to define a car.
//
class Car {
  Car({
    required this.make,
    required this.colour,
    required this.engineSize,
    required this.cost,
    required this.ageInYears,
    required this.mileage,
    required this.mpg,
  });
  final String make;
  final String colour;
  final int engineSize;
  final double cost;
  final int ageInYears;
  final int mileage;
  final double mpg;
}



double milesPerYear() {
  double milesPerYear = ${this.mileage} / ${this.ageInYears};
  return milesPerYear;

  // this line does not work. Is it possible to use the 'mileage' and 'ageInYears' data 
  // from when the car object was instantiated/
  
}

void main() {
  print("dart /car/main.dart");

  final aCar = Car(
      make: "Vaxhall",
      colour: "Silver",
      engineSize: 1400,
      cost: 7000,
      ageInYears: 19,
      mileage: 60000,
      mpg: 20);

  // costPerYear(double cost, int age)
  print(aCar.make);
  print(costOfPurchase(7000, 19));
  print(costPerMile(7000, 60000));
  print(milesPerYear());


  // a line to invoke the function 'milesPerYear'
  print(milesPerYear()); 

  // this line does not work. How can I invoke the function and have it use the data 
  // created when the object was instantiated?
}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source