How to access widget in an initializer in google maps flutter

Viewed 26

I am passing select latitude and longitude from google maps to my flutter app's another screen where I am calculating the distance between 2 locations. I've got the values coming fine but there's this widget can't be accessed in an initializer issue coming. I'm using google maps and I've to pass the widget.lat widget.long values to the userLocation marker.

I'm using this tutorial's code by the way Get distance between locations

Here's my code

class CalculateDistance extends StatefulWidget {
  const CalculateDistance({super.key, required this.lang, required this.lat});

  final double lang;
  final double lat;
  @override
  // ignore: library_private_types_in_public_api
  _CalculateDistanceState createState() => _CalculateDistanceState();
}

class _CalculateDistanceState extends State<CalculateDistance> {
  GoogleMapController? mapController; //contrller for Google map
  PolylinePoints polylinePoints = PolylinePoints();

  String googleAPiKey = "YOUR_API_KEY";

  Set<Marker> markers = {}; //markers for google map
  Map<PolylineId, Polyline> polylines = {}; //polylines to show direction
  LatLng storeLocation =
      const LatLng(-30.600164342582726, 23.508854043469647); // Store location
// This is where I can't use the passed values
  LatLng userLocation = LatLng(widget.lat, widget.lang); // User location

  double distance = 0.0;

  @override
  void initState() {
    markers.add(Marker(
      //add start location marker
      markerId: MarkerId(storeLocation.toString()),
      position: storeLocation, //position of marker
      infoWindow: const InfoWindow(
        //popup info
        title: 'Store Location',
        snippet: 'Store Marker',
      ),
      icon: BitmapDescriptor.defaultMarker, //Icon for Marker
    ));

    markers.add(Marker(
      //add distination location marker
      markerId: MarkerId(userLocation.toString()),
      position: userLocation, //position of marker
      infoWindow: const InfoWindow(
        //popup info
        title: 'User Location',
        snippet: 'User Marker',
      ),
      icon: BitmapDescriptor.defaultMarker, //Icon for Marker
    ));

    getDirections(); //fetch direction polylines from Google API

    super.initState();
  }

  getDirections() async {
    List<LatLng> polylineCoordinates = [];

    PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
      googleAPiKey,
      PointLatLng(storeLocation.latitude, storeLocation.longitude),
      PointLatLng(userLocation.latitude, userLocation.longitude),
      travelMode: TravelMode.driving,
    );

    if (result.points.isNotEmpty) {
      for (var point in result.points) {
        polylineCoordinates.add(LatLng(point.latitude, point.longitude));
      }
    } else {
      print(result.errorMessage);
    }

    //polulineCoordinates is the List of longitute and latidtude.
    double totalDistance = 0;
    for (var i = 0; i < polylineCoordinates.length - 1; i++) {
      totalDistance += calculateDistance(
          polylineCoordinates[i].latitude,
          polylineCoordinates[i].longitude,
          polylineCoordinates[i + 1].latitude,
          polylineCoordinates[i + 1].longitude);
    }
    print(totalDistance);

    setState(() {
      distance = totalDistance;
    });

    //add to the list of poly line coordinates
    addPolyLine(polylineCoordinates);
  }

  addPolyLine(List<LatLng> polylineCoordinates) {
    PolylineId id = const PolylineId("poly");
    Polyline polyline = Polyline(
      polylineId: id,
      color: Colors.deepPurpleAccent,
      points: polylineCoordinates,
      width: 8,
    );
    polylines[id] = polyline;
    setState(() {});
  }

  double calculateDistance(lat1, lon1, lat2, lon2) {
    var p = 0.017453292519943295;
    var a = 0.5 -
        cos((lat2 - lat1) * p) / 2 +
        cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2;
    return 12742 * asin(sqrt(a));
  }
  // Scaffold ahead
1 Answers

Declare this LatLng with late keyword as a member of _CalculateDistanceState class:

class _CalculateDistanceState extends State<CalculateDistance> {
  late LatLng _userLocation;
  (...)
}

Then in the initState you will have access to the widget:

void initState() {
  super.initState();
  _userLocation = LatLng(widget.lat, widget.lang);
  (...)
}
Related