我正在使用google_maps_flutter插件来使用谷歌Map,我按照他们的指示设置了minSdkVersion
,并在AndroidManifest.xml文件中包含了API密钥。我正在使用他们的示例代码来测试插件,但我在调试控制台中不断收到这些错误
E/flutter (16699): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Bad state: Future already completed
E/flutter (16699): #0 _AsyncCompleter.complete (dart:async/future_impl.dart:35:31)
E/flutter (16699): #1 _GoogleMapState.onPlatformViewCreated
package:google_maps_flutter/src/google_map.dart:413
E/flutter (16699): <asynchronous suspension>
E/flutter (16699):
main.dart(我从插件页面获得)
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Google Maps Demo',
home: MapSample(),
);
}
}
class MapSample extends StatefulWidget {
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample> {
Completer<GoogleMapController> _controller = Completer();
static final CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
);
static final CameraPosition _kLake = CameraPosition(
bearing: 192.8334901395799,
target: LatLng(37.43296265331129, -122.08832357078792),
tilt: 59.440717697143555,
zoom: 19.151926040649414);
@override
Widget build(BuildContext context) {
return new Scaffold(
body: GoogleMap(
mapType: MapType.hybrid,
initialCameraPosition: _kGooglePlex,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _goToTheLake,
label: Text('To the lake!'),
icon: Icon(Icons.directions_boat),
),
);
}
Future<void> _goToTheLake() async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(_kLake));
}
}
我调试了一下发现
GoogleMap(
mapType: MapType.hybrid,
initialCameraPosition: _kGooglePlex,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
在我的主要.dart文件是导致错误,当我删除它,我没有得到错误,但没有Map以及。
此外,当我按照调试控制台中提供的链接进行操作时
E/flutter (16699): #1 _GoogleMapState.onPlatformViewCreated
package:google_maps_flutter/src/google_map.dart:413
它向我显示了这个函数,我认为它是导致未来错误的根本问题
Future<void> onPlatformViewCreated(int id) async {
final GoogleMapController controller = await GoogleMapController.init(
id,
widget.initialCameraPosition,
this,
);
_controller.complete(controller);
_updateTileOverlays();
final MapCreatedCallback? onMapCreated = widget.onMapCreated;
if (onMapCreated != null) {
onMapCreated(controller);
}
}
并突出显示第413行,
_controller.complete(controller);
1条答案
按热度按时间bxgwgixi1#
尝试在
MapSampleState
类中将GoogleMapController
声明为late
变量,而不是使用Completer
:并更新
onMapCreated
函数:我不知道你的代码有什么问题,但它对我的工作方式(Flutter3.3.8,google_maps_flutter 2.2.1)。
如果它能工作,请确保在创建控制器之前不要尝试使用它,否则会出现延迟初始化错误。或者,可以将
_controller
声明为可空,并在尝试使用它之前检查它是否为空: