Moh*_*bil 0 location dart flutter
我正在使用此库在谷歌地图上显示我当前的位置:package:location/location.dart。酒吧开发链接
问题是每当我在发布模式下打开应用程序时,它就会崩溃并显示:
LateInitializationError:字段“currentLatLng”尚未初始化
它不会在 Android 设备上的调试模式下崩溃。然而,它确实会在 iOS 上崩溃(发布和调试模式)。
我不确定我做错了什么。这是我的小部件和尝试:
class TestGoogle extends StatefulWidget {
const TestGoogle({Key? key}) : super(key: key);
@override
_TestGoogleState createState() => _TestGoogleState();
}
class _TestGoogleState extends State<TestGoogle> {
late LatLng currentLatLng;
late GoogleMapController mapController;
Location location = new Location();
var latitude;
var longitude;
late LocationData _locationData;
get() async {
_locationData = await location.getLocation();
latitude = _locationData.latitude;
longitude = _locationData.longitude;
setState(() {
currentLatLng = new LatLng(latitude, longitude);
});
}
@override
initState() {
super.initState();
get();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: GoogleMap(
myLocationEnabled: true,
onCameraMove: (CameraPosition cameraPosition) {
print(cameraPosition.zoom);
},
initialCameraPosition:
CameraPosition(target: currentLatLng, zoom: 15.0),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
下面的代码应该可以解决您的问题。您的问题原因,请在初始化之前尝试使用变量。
class TestGoogle extends StatelessWidget {
TestGoogle({Key? key}) : super(key: key);
late GoogleMapController mapController;
Location location = Location();
Future<LatLng> get() async {
final _locationData = await location.getLocation();
return LatLng(_locationData.latitude, _locationData.longitude);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<LatLng>(
future: get(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final locationModel = snapshot.data!;
final latitude = locationModel.latitude;
final longitude = locationModel.longitude;
return GoogleMap(
myLocationEnabled: true,
onCameraMove: (CameraPosition cameraPosition) {
print(cameraPosition.zoom);
},
initialCameraPosition: CameraPosition(target: locationModel, zoom: 15.0),
);
}
return const CircularProgressIndicator();
},
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1465 次 |
| 最近记录: |