Abderrezak Douba
Abderrezak Douba

Reputation: 115

Null check operator used on a null value . where is the problem

i want to show a map with marker on the user current location but it won't for some reason the map work well but the marker for the user when i try to show it i face this error

am facing the error in those specific lines

Latlng(currentposition!.latitude, currentposition!.longitude, ) in both center and marker

location: ^5.0.3 flutter_map: ^5.0.0 flutter_osm_plugin: ^0.60.5 latlong2: ^0.9.0 geolocator: ^10.1.0 permission_handler: ^10.4.5

import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class map extends StatefulWidget {
  const map({super.key});

  @override
  State<map> createState() => _mapState();
}

class _mapState extends State<map> {
  MapController mapController = MapController();
  Position? currentposition;

  void getCurrentPosition() async {
    bool serviceEnabling = await Geolocator.isLocationServiceEnabled();
    PermissionStatus status = await Permission.location.request();
    if (status.isDenied && !serviceEnabling) {
      return print('access deniad');
    }
    if (status.isGranted) {
      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
      );
      setState(() {
        currentposition = position;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        FlutterMap(
          mapController: mapController,
          options: MapOptions(
            center: LatLng(
              currentposition!.latitude,
              currentposition!.longitude,
            ),
            zoom: 16.0,
            maxZoom: 19,
            minZoom: 13,
          ),
          children: [
            TileLayer(
              urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
              subdomains: ['a', 'b', 'c'],
            ),
            MarkerLayer(
              markers: currentposition != null
                  ? [
                      Marker(
                        height: 80.0,
                        width: 80.0,
                        point: LatLng(
                          currentposition!.longitude,
                          currentposition!.latitude,
                        ),
                        builder: (ctx) => Container(
                          child: const Icon(Icons.location_on),
                        ),
                      ),
                    ]
                  : [],
            )
          ],
        ),
       
      ],
    );
  }
}


```!

Upvotes: 1

Views: 118

Answers (2)

Keval
Keval

Reputation: 76

The method getCurrentPosition() is Future method, it will take some time to fetch the data, so what you can do is you can use the FutureBuilder to resolve the issue another solution is to add the initial latitude and longitude values in the start of executing build method like below-mentioned example and when you get both values (lat/long) through current positions at that time you can update your UI

 @override
  Widget build(BuildContext context) {
    LatLng initialPosition = LatLng(0, 0); // Default position

    if (currentposition != null) {
      initialPosition = LatLng(
        currentposition!.latitude,
        currentposition!.longitude,
      );
    }

    return YourWidgetTree();

Upvotes: 1

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63749

getCurrentPosition() is a future method, It will take some time to get the data. But using currentposition! on LatLng seeking it on 1st frame which is causing the issue.

Best option will be using FutureBuilder for this. Also you can do a null check

options: MapOptions(
center: currentposition == null
    ? null
    : LatLng(
        currentposition!.latitude,
        currentposition!.longitude,
      ),

Upvotes: 1

Related Questions