0

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The getter 'latitude' was called on null. E/flutter ( 8159): Receiver: null E/flutter ( 8159): Tried calling: latitude

Here's My Code Snippet:

class CustomAppBar extends StatelessWidget {
  const CustomAppBar({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    FirebaseService _service = FirebaseService();

    return FutureBuilder<DocumentSnapshot>(
      future: _service.users.doc(_service.user.uid).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.hasData && !snapshot.data.exists) {
          return Text("Address not selected");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data = snapshot.data.data() as Map<String, dynamic>;

          if(data['address']==null){
            if(data['state']==null){
              GeoPoint latLong = data['location'];
              _service.getAddress(latLong.latitude, latLong.longitude).then((adres) {
                appBar(adres, context);
              });
            }
          }else{
            return appBar(data['address'], context);
          }

        }

        return Text("Fetching Location");
      },
    );
  }
Bach
  • 2,928
  • 1
  • 6
  • 16
  • The error indicated that `GeoPoint latLong = data['location']` latLong is null. – 聂超群 Dec 13 '21 at 07:23
  • Does this answer your question? [What is a NoSuchMethod error and how do I fix it?](https://stackoverflow.com/questions/64049102/what-is-a-nosuchmethod-error-and-how-do-i-fix-it) – nvoigt Dec 13 '21 at 08:23

1 Answers1

0

The error is caused by this line:

// ... other lines
_service.getAddress(latLong.latitude, latLong.longitude).then((adres) {
    appBar(adres, context);
});

in particular the latLong.latitude.

This is because your latLong is null due to data['location'] is null. You need to add a check before the block such as if (data['location'] != null) or use null-safe feature:

// Take default lat, long as 0.0 in case they are null
_service.getAddress(latLong?.latitude ?? 0.0, latLong?.longitude ?? 0.0).then((adres) {
    appBar(adres, context);
});

Then the error would go away.

Bach
  • 2,928
  • 1
  • 6
  • 16