convertFuelEconomy function Null safety

double convertFuelEconomy(
  1. FuelEconomy from,
  2. FuelEconomy to,
  3. double value
)

Convert Fuel economy. It may lose some decimals in the proccess.

from, to and value can NOT be null, otherwise an AssertionError is thrown

Basic usage:

main() {
 final fuel = convertFuelEconomy(
   FuelEconomy.kilometerPerLitre, // from
   FuelEconomy.milePerUsGallon, // to
   1, // value
 );
 print(fuel); // 2,35215
}

Read the documentation for more information

Implementation

double convertFuelEconomy(
  FuelEconomy from,
  FuelEconomy to,
  double value,
) {
  verify(from, to, value);
  if (from == to) return value;
  if (from == FuelEconomy.kilometerPerLitre) {
    switch (to) {
      case FuelEconomy.literPer100Kilometres:
        return value * 100;
      case FuelEconomy.milePerUsGallon:
        return value * 2.352;
      case FuelEconomy.milePerImperialGallon:
        return value * 2.825;
      default:
        return value;
    }
  } else {
    // always convert to liter per liter
    // to convert to the needed value
    // may lost a few decimals in the proccess
    final litre = FuelEconomy.kilometerPerLitre;
    switch (from) {
      case FuelEconomy.literPer100Kilometres:
        return convertFuelEconomy(litre, to, value / 100);
      case FuelEconomy.milePerUsGallon:
        return convertFuelEconomy(litre, to, value / 2.352);
      case FuelEconomy.milePerImperialGallon:
        return convertFuelEconomy(litre, to, value / 2.825);
      default:
        return value;
    }
  }
}