对空值使用空检查运算符。问题出在哪里

问题描述 投票:0回答:1

我想在用户当前位置显示带有标记的地图,但由于某种原因不会 地图工作得很好,但是当我尝试向用户显示它时,我面临这个错误

我面临这些特定行中的错误

Latlng(当前位置!.纬度, 当前位置!.经度,) 在中心和标记处

地点:^5.0.3 flutter_map:^5.0.0 flutter_osm_plugin:^0.60.5 经纬度2:^0.9.0 地理定位器:^10.1.0 权限处理程序:^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),
                        ),
                      ),
                    ]
                  : [],
            )
          ],
        ),
       
      ],
    );
  }
}


```!

flutter openstreetmap fluttermap
1个回答
0
投票

getCurrentPosition()
是未来的方法,需要一些时间才能获取数据。但是在
currentposition!
上使用
LatLng
在第一帧上寻找它,这导致了问题。

最好的选择是使用 FutureBuilder。您也可以进行空检查

options: MapOptions(
center: currentposition == null
    ? null
    : LatLng(
        currentposition!.latitude,
        currentposition!.longitude,
      ),
© www.soinside.com 2019 - 2024. All rights reserved.