milesabc123
milesabc123

Reputation: 85

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?
}

Upvotes: 0

Views: 36

Answers (1)

julemand101
julemand101

Reputation: 31219

Your milesPerYear() method is outside the class. Your Car class should instead be the following if you want to be able to call the method on car objects and have access to this (which points to the Car object the method is called on):

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() {
    return mileage / ageInYears;
  }

  // Or the following if you want it even shorter:
  // double milesPerYear() => mileage / ageInYears;

  // Or really, it should just be a getter and not a method
  // double get milesPerYear => mileage / ageInYears;
}

By having the method inside the class, you can then call the method on object instances of Car like: aCar.milesPerYear().

Upvotes: 1

Related Questions