You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>

疑问

  1. 如何解决上述Bad state: No element异常?
  2. 从Google凭据页面获取API密钥后,直接传入Geocoder2的getDataFromCoordinates方法中,这种使用方式是否正确?

内容的提问来源于stack exchange,提问作者Pratishtha S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 02:15:39