The property 'latitude' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.')

Issue

I am facing a null safety issue in Text(
"Latitude: " + currentPosition.latitude.toString(),
) this line. i dont know how to make currentPosition.latitude not null help me with this guys.

It gives me this The property ‘latitude’ can’t be unconditionally accessed because the receiver can be ‘null’.
Try making the access conditional (using ‘?.’) or adding a null check to the target (‘!’). error.

The property ‘longitude’ can’t be unconditionally accessed because the receiver can be ‘null’.
Try making the access conditional (using ‘?.’) or adding a null check to the target (‘!’). error

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeApp(),
    );
  }
}

class HomeApp extends StatefulWidget {
  HomeApp({Key? key}) : super(key: key);

  @override
  State<HomeApp> createState() => _HomeAppState();
}

class _HomeAppState extends State<HomeApp> {
  String currentAddress = 'my address';
  Position? currentPosition;
  Future<Position?> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      Fluttertoast.showToast(msg: 'Please keep your location on.');
    }
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        Fluttertoast.showToast(msg: 'Location permission is denied.');
      }
    }
    if (permission == LocationPermission.deniedForever) {
      Fluttertoast.showToast(msg: 'Location permission is denies forever.');
    }
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    try {
      List<Placemark> placemark =
          await placemarkFromCoordinates(position.latitude, position.longitude);
      Placemark place = placemark[0];
      setState(() {
        currentPosition = position;
        currentAddress =
            "${place.locality},${place.postalCode},${place.country}";
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Location App'),
      ),
      body: Center(
        child: Column(
          children: [
            Text(
              currentAddress,
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            (currentPosition != null)
                ? Text(
                    "Latitude: " + currentPosition.latitude.toString(),
                  )
                : Container(),
            (currentPosition != null)
                ? Text(
                    "Longitude: " + currentPosition.longitude.toString(),
                  )
                : Container(),
            TextButton(
              onPressed: () {
                _determinePosition();
              },
              child: Text('Locate Me'),
            ),
          ],
        ),
      ),
    );
  }
}

Solution

Change to this:

 currentPosition!.latitude.toString()

Since you check that currentPosition is not null, you can use the ! as a way of saying "I know it can be null, but I also know that at this point it definitely isn’t".

Answered By – Tim Jacobs

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.