Home > Software engineering >  i got an constant error in code. The default value of an optional parameter must be constant
i got an constant error in code. The default value of an optional parameter must be constant

Time:09-16

i hava an error in this code.

MapScreen({
    this.initialLocation =
     const PlaceLocation (latitude: 37.422, longitude: -122.084, address: ''),
    this.isSelecting = false,
  });

i'll be appreciate if you help <3

CodePudding user response:

welcome. Dart requires that default argument values be compile-time constants, and PlaceLocation(latitude: 37.422, longitude: -122.084, address: ''), cannot be determined at compilation time since it depends on parameters.

try

MapScreen({
this.isSelecting = false,
 }): initialLocation = PlaceLocation (latitude: 37.422, longitude: -122.084, 
 address:'');

CodePudding user response:

Not sure why your code doesn't work. I don't know what your classes fully look like but this minimal working example with identical constructor as yours works fine:

class MapScreen {
  final PlaceLocation initialLocation;
  final bool isSelecting;

  MapScreen({
    this.initialLocation =
     const PlaceLocation(latitude: 37.422, longitude: -122.084, address: ''),
    this.isSelecting = false,
  });
}

class PlaceLocation {
  final double latitude;
  final double longitude;
  final String address;

  const PlaceLocation({this.latitude = 0, this.longitude = 0, this.address = ""});
}

@brook yonas's answer is correct when PlaceLocation can't be a compile-time constant. But your code suggests that it should be able to be constant because you use the const keyword.

  • Related