avish
avish

Reputation: 35

Error when passing latitude and longitude to Latlng in flutter

I am trying to refactor my code and have separated the showMap class to a new dart file. I am passing latitude and longitude from screen on which this class is being called to showMap. I have checked that latitude and longitude here are not null. But i am getting an error saying:

The following NoSuchMethodError was thrown building showMap(dirty): The method 'compareTo' was called on null. Receiver: null Tried calling: compareTo(-90.0)

class showMap extends StatelessWidget {
  showMap({this.latitude, this.longitude});
  double latitude;
  double longitude;

  @override
  Widget build(BuildContext context) {
    return FlutterMap(
      options: MapOptions(
        center: LatLng(latitude, longitude), // The Error line
        zoom: 16.0,
      ),
      layers: [
        TileLayerOptions(
            urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
            subdomains: ['a', 'b', 'c']),
        MarkerLayerOptions(
          markers: [
            Marker(
              width: 80.0,
              height: 80.0,
              point: LatLng(58.7041, 37.1025),
              builder: (ctx) => GestureDetector(
                child: Container(
                  child: Icon(
                    Icons.location_on,
                    size: 60,
                    color: Color(0xFF744D81),
                  ),
                ),
                onTap: () {
                  showModalBottomSheet(
                      context: context,
                      builder: (context) {
                        return MarkerPopup();
                      });
                },
              ),
            ),
            Marker(
              width: 80.0,
              height: 80.0,
              point: LatLng(58.4419, 37.0784),
              builder: (ctx) => GestureDetector(
                child: Container(
                  child: Icon(Icons.location_on,
                      size: 60, color: Color(0xFF744D81)),
                ),
                onTap: () {
                  showModalBottomSheet(
                      context: context,
                      builder: (context) {
                        return MarkerPopup();
                      });
                },
              ),
            ),
          ],
        ),
      ],
    );
  }
}

Here is the part of the code where showMap is being called:

class _HomePageState extends State<HomePage> {

  void getLocation() async {
    Location location = Location();
    await location.getCurrrentLocation();
    latitude = location.latitude;
    longitude = location.longitude;
  }

  @override
  void initState() {
    super.initState();
    getLocation();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Udan'),
        backgroundColor: Color(0xFF4E295B),
        centerTitle: true,
      ),
      
      body: Stack(
        children: <Widget>[
          showMap(
            latitude: latitude,
            longitude: longitude,
          ),
        ],
      ),
    );
  }
}


Peculiar thing is that after a second or two, the error goes away and map is loaded at the correct center. But in the meanwhile, the code breaks and screen shows the error. I am guessing it's because it takes time to fetch the location and null values of latitude and longitude are passed on until the location is fetched. I have already used async await in the original screen before assigning value to showMap. How do i get this to work? Thanks.

Upvotes: 1

Views: 2410

Answers (2)

MindStudio
MindStudio

Reputation: 786

showMap() is called before any location data exists. You should wait for the location data and then build the map with the data. This can be done using a FutureBuilder:

First, you should create a future.

Future<Location> getLocation = Future<Location>() async {
    Location location = new Location();
    var serviceEnabled = await location.serviceEnabled();
    if (!serviceEnabled) {
      serviceEnabled = await location.requestService();
      if (!serviceEnabled) {
        return null;
      }
    }
    var currentLocation = await location.getLocation();
    return currentLocation;
  }

Then return a FutureBuilder in place of showMap():

FutureBuilder<Location>(
        future: getLocation(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return showMap(latitude: snapshot.data.latitude, longitude: snapshot.data.longitude);
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        });

I am unable to verify my code since i can't get the location package to work. If you find any errors I will gladly edit my answer.

Upvotes: 0

glavigno
glavigno

Reputation: 503

The method getLocation contains an async operation and the build method executes before it has resolved.

An option could be to display a loader while latitude and longitude are null. Once the future location.getCurrrentLocation is resolved, you can call showMap.

Upvotes: 1

Related Questions