目的是加载页面并根据设备的 GPS 在 Google 地图中显示当前位置。
下面的代码有什么问题?看来它不想等待位置并返回“空值检查运算符使用于空值”。
我无法找到答案,希望得到一些帮助。
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
class FindSomeonePage extends StatefulWidget {
const FindSomeonePage({Key? key}) : super(key: key);
@override
State<FindSomeonePage> createState() => _FindSomeonePageState();
}
class _FindSomeonePageState extends State<FindSomeonePage> {
LatLng? _initialLocation;
late GoogleMapController mapController;
@override
void initState() {
super.initState();
_setInitialLocation();
}
_setInitialLocation() async {
LocationData? currentLocation = await getCurrentLocation();
if (currentLocation != null) {
setState(() {
_initialLocation =
LatLng(currentLocation.latitude!, currentLocation.longitude!);
});
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Stack(
children: [
GoogleMap(
//LatLng(-15.4630239974464, 28.363397732282127)
initialCameraPosition: CameraPosition(
target: _initialLocation!,
zoom: 15.0,
),
onMapCreated: (controller) {
mapController = controller;
},
),
],
),
),
);
}
}
Future<LocationData?> getCurrentLocation() async {
Location location = new Location();
bool _serviceEnabled;
PermissionStatus _permissionGranted;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return null;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return null;
}
}
return await location.getLocation();
}
您收到该错误是因为
_initialLocation
最初为空,并且您在小部件的主体中使用它,而没有检查该值是否为空,也没有等待 getCurrentLocation()
的结果。
要解决此问题,您需要在获取
currentLocation
时向您的小部件显示加载微调器。
首先,初始化一个
_isLoading
变量:
bool _isLoading = false;
那么你的
_setInitialLocation
应该是:
_setInitialLocation() async {
_isLoading = true;
LocationData? currentLocation = await getCurrentLocation();
if (currentLocation != null) {
_initialLocation =
LatLng(currentLocation.latitude!, currentLocation.longitude!);
}
///this rebuilds your widget whether or not the fetch location is successful
///It is then your responsibility to show error to your widget when error occur.
setState(() {
_isLoading = false;
});
}
你的小部件的主体应该是:
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: _isLoading ? CircularProgressIndicator() : Stack(
children: [
if(_initialLocation != null)...[
GoogleMap(
//LatLng(-15.4630239974464, 28.363397732282127)
initialCameraPosition: CameraPosition(
target: _initialLocation!,
zoom: 15.0,
),
onMapCreated: (controller) {
mapController = controller;
},
),
]
],
),
),
);
}
}