【发布时间】:2021-11-27 11:59:01
【问题描述】:
我一直在尝试制作一个可以获取用户位置并将其转换为本地地址的应用程序。我不明白这里的错误以及如何解决它。 错误:LateInitializationError: Field 'currentposition' has not been initialized.
我正在尝试使用 setState 下的当前位置来显示地区、子地区、街道名称和邮政编码,但即使这样仍然会抛出错误。 我在一开始就将其定义为 String currentAddress = 'My Address'; 后期位置当前位置;
我已附上以下代码。
我正在使用 Geolocator 作为定位服务和地理编码来将该信息转换为地址。
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String currentAddress = 'My Address';
late Position currentposition ;
Future<Position?> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
Fluttertoast.showToast(msg: 'Please enable Your Location Service');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
Fluttertoast.showToast(msg: 'Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
Fluttertoast.showToast(
msg:
'Location permissions are permanently denied, we cannot request permissions.');
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
try {
List<Placemark> placemarks =
await placemarkFromCoordinates(position.latitude, position.longitude);
Placemark place = placemarks[0];
setState(() {
currentposition = position;
currentAddress =
"${place.locality}, ${place.subLocality},${place.street}, ${place.postalCode}";
});
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Location'),
),
body: Center(
child: Column(
children: [
Text(currentAddress),
currentposition != null
? Text('Latitude = ' + currentposition.latitude.toString())
: Container(),
currentposition != null
? Text('Longitude = ' + currentposition.longitude.toString())
: Container(),
TextButton(
onPressed: () {
_determinePosition();
},
child: Text('Locate me'))
],
),),
);
}
}
【问题讨论】:
-
请改用
Position? currentposition;。无论如何,您都在进行空值检查。没有理由不能为空。