Flutter使用Geocoder2触发Bad state: No element异常求助
问题描述
在Flutter项目中使用Geocoder2插件,运行应用并点击地图不同位置时,抛出Unhandled Exception: Bad state: No element异常。
代码片段
变量定义
LatLng point=LatLng(40, -1); GeoData? location;
FlutterMap组件
FlutterMap( options: MapOptions( onTap: (p, point) async { location = await Geocoder2.getDataFromCoordinates( latitude: point.latitude, longitude: point.longitude, googleMapApiKey: 'GOOGLE API KEY'); print("${location?.country}"); setState((){ point=p as LatLng; }); }, center: LatLng(40, -1), zoom: 15.0 ), layers: [ TileLayerOptions( urlTemplate: "URL", subdomains: ['a','b','c'], ), MarkerLayerOptions(markers: [ Marker( width:200.0, height:200.0, point: point, builder: (ctx)=> Icon( Icons.location_on, color: Colors.red, size:40.0, )), ], ), ], ),
位置信息展示组件
Card(child: Padding( padding: EdgeInsets.all(16.0), child: Text("${location?.country}, ${location?.city}, ${location?.state}", style: TextStyle(fontWeight: FontWeight.bold),), ),)
关键异常日志
E/flutter ( 4093): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Bad state: No element E/flutter ( 4093): #0 List.first (dart:core-patch/growable_array.dart:343:5) E/flutter ( 4093): #1 Geocoder2.getDataFromCoordinates (package:geocoder2/src/geocoder2.dart:24:44) E/flutter ( 4093): <asynchronous suspension> E/flutter ( 4093): #2 _HomePageState.build.<anonymous closure> (package:mfieldtrip/Home.dart:124:26) E/flutter ( 4093): <asynchronous suspension>
疑问
- 如何解决上述
Bad state: No element异常? - 从Google凭据页面获取API密钥后,直接传入Geocoder2的
getDataFromCoordinates方法中,这种使用方式是否正确?
内容的提问来源于stack exchange,提问作者Pratishtha S
相关产品推荐
相关产品推荐

