提问人:Abderrezak Douba 提问时间:10/5/2023 更新时间:10/5/2023 访问量:53
对 null 值 使用的 Null 检查运算符。问题出在哪里
Null check operator used on a null value . where is the problem
问:
我想在用户当前位置上显示带有标记的地图,但由于某种原因无法显示 地图运行良好,但是当我尝试显示用户的标记时,我遇到了此错误
我面临这些特定行中的错误
Latlng(当前位置!.纬度 当前位置!.经度, ) 在中心和标记中
位置: ^5.0.3 flutter_map: ^5.0.0 flutter_osm_plugin: ^0.60.5 纬度2:^0.9.0 地理定位器:^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),
),
),
]
: [],
)
],
),
],
);
}
}
```!
答:
1赞
Md. Yeasin Sheikh
10/5/2023
#1
getCurrentPosition()
是将来的方法,获取数据需要一些时间。但是在第一帧上使用搜索它会导致问题。currentposition!
LatLng
最好的选择是使用 FutureBuilder。您也可以进行 null 检查
options: MapOptions(
center: currentposition == null
? null
: LatLng(
currentposition!.latitude,
currentposition!.longitude,
),
评论
0赞
Abderrezak Douba
10/5/2023
我也可以在记号笔上使用它吗
0赞
Md. Yeasin Sheikh
10/5/2023
当然,但你已经在这样做了markers: currentposition != null
0赞
Abderrezak Douba
10/5/2023
还是不行
0赞
Md. Yeasin Sheikh
10/6/2023
从您当前的上下文中,我只能说这是问题所在,您可以在不检查 null 的情况下检查使用 null 断言的其他部分!
1赞
Keval
10/5/2023
#2
方法是方法,获取数据需要一些时间,所以你可以做的是你可以使用 FutureBuilder 来解决这个问题,另一个解决方案是在执行构建方法的开始添加初始纬度和经度值,如下图所示,当你通过当前位置获得这两个值(纬度/经度)时,你可以更新你的 UIgetCurrentPosition()
Future
@override
Widget build(BuildContext context) {
LatLng initialPosition = LatLng(0, 0); // Default position
if (currentposition != null) {
initialPosition = LatLng(
currentposition!.latitude,
currentposition!.longitude,
);
}
return YourWidgetTree();
评论
0赞
Abderrezak Douba
10/5/2023
它起作用了,但标记不会出现
评论