Flutter / dart异常地理定位错误

Posted

技术标签:

【中文标题】Flutter / dart异常地理定位错误【英文标题】:Flutter / dart exception geolocation error 【发布时间】:2018-09-18 20:33:30 【问题描述】:

我在使用地理定位时遇到了颤振/飞镖的问题。我已按照一门 Udemy 课程的说明进行操作,但我遇到了此错误。软件包已上传,代码与讲师代码完全相似,尽管它不起作用。我还尝试通过在终端中输入:“flutter clean”来清理构建文件,也没有解决问题。如果我需要发布更多信息,请告诉我。谢谢你的时间 。干杯

[VERBOSE-2:shell.cc(181)] Dart Error: Unhandled exception:
RangeError (index): Invalid value: Valid value range is empty: 0
#0      List.[] (dart:core/runtime/libgrowable_array.dart:142:60)
#1      _LocationInputState._getStaticMap (file:///Users/matija/Documents/Development/artapica/lib/widgets/form_inputs/location.dart:64:37)
<asynchronous suspension>
#2      _LocationInputState._updateLocation (file:///Users/matija/Documents/Development/artapica/lib/widgets/form_inputs/location.dart:124:7)
#3      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:161:21)
#4      FocusNode._notify (package:flutter/src/widgets/focus_manager.dart:103:5)
#5      FocusManager._update (package:flutter/src/widgets/focus_manager.dart:449:20)
#6      _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#7      _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)

Location.dart

class LocationInput extends StatefulWidget

 
  final Function setLocation;
  final Product product;

  LocationInput(this.setLocation, this.product);

  @override
  State<StatefulWidget> createState() 
    return _LocationInputState();
  


class _LocationInputState extends State<LocationInput> 
  Uri _staticMapUri;
  LocationData _locationData;
  final FocusNode _addressInputFocusNode = FocusNode();
  final TextEditingController _addressInputController = 
 TextEditingController();

  @override
 void initState() 
   _addressInputFocusNode.addListener(_updateLocation);
    if (widget.product != null) 
     _getStaticMap(widget.product.location.address, geocode: false);
   
    super.initState();
 

 @override
  void dispose() 
   _addressInputFocusNode.removeListener(_updateLocation);
     super.dispose();
   
  void _getStaticMap(String address,
       bool geocode = true, double lat, double lng) async 
       if (address.isEmpty) 
       setState(() 
        _staticMapUri = null;
      );
     widget.setLocation(null);
     return;
    
     if (geocode) 
       final Uri uri = Uri.https(
        'maps.googleapis.com',
       '/maps/api/geocode/json',
    'address': address, 'key': 'MYKEY',
  );
  final http.Response response = await http.get(uri);
  final decodedResponse = json.decode(response.body);
  final formattedAddress =
      decodedResponse['results'][0]['formatted_address'];
  final coords = decodedResponse['results'][0]['geometry']['location'];
  _locationData = LocationData(
      address: formattedAddress,
      latitude: coords['lat'],
      longitude: coords['lng']);
 else if (lat == null && lng == null) 
  _locationData = widget.product.location;
 else 
  _locationData =
      LocationData(address: address, latitude: lat, longitude: lng);


if (mounted) 
  final StaticMapProvider staticMapViewProvider =
      StaticMapProvider('MYKEY');
  final Uri staticMapUri = staticMapViewProvider.getStaticUriWithMarkers([
    Marker('position', 'Position', _locationData.latitude,
        _locationData.longitude)
  ],
      center: Location(_locationData.latitude, _locationData.longitude),
      width: 500,
      height: 300,
      maptype: StaticMapViewType.roadmap);
  widget.setLocation(_locationData);

  setState(() 
    _addressInputController.text = _locationData.address;
    _staticMapUri = staticMapUri;
      );
    
   
         Future<String> _getAddress(double lat, double lng) async 
         final uri = Uri.https(
          'maps.googleapis.com',
           '/maps/api/geocode/json',
             
          'latlng': '$lat.toString(),$lng.toString()',
           'key': 'MYKEY'
      ,
     );
    final http.Response response = await http.get(uri);
    final decodedResponse = json.decode(response.body);
     final formattedAddress = decodedResponse['results'][0] 
     ['formatted_address'];
      return formattedAddress;
    

   void _getUserLocation() async 
final location = geoloc.Location();
final currentLocation = await location.getLocation();
final address = await _getAddress(
    currentLocation['latitude'], currentLocation['longitude']);
_getStaticMap(address,
    geocode: false,
    lat: currentLocation['latitude'],
    lng: currentLocation['longitude']);
   

  void _updateLocation() 
if (!_addressInputFocusNode.hasFocus) 
  _getStaticMap(_addressInputController.text);
    
    

   @override
  Widget build(BuildContext context) 
    return Column(
      children: <Widget>[
        EnsureVisibleWhenFocused(
          focusNode: _addressInputFocusNode,
      child: TextFormField(
        focusNode: _addressInputFocusNode,
        controller: _addressInputController,
        validator: (String value) 
          if (_locationData == null || value.isEmpty) 
            return 'No valid location found.';
          
        ,
        decoration: InputDecoration(labelText: 'Address'),
      ),
    ),
    SizedBox(height: 10.0),
    FlatButton(
      child: Text('Locate User'),
      onPressed: _getUserLocation,
    ),
    SizedBox(
      height: 10.0,
    ),
    _staticMapUri == null
        ? Container()
        : Image.network(_staticMapUri.toString())
  ],
);
  
    

【问题讨论】:

无法为您提供任何帮助,除非您分享 location.dart 我添加了 location.dart 。 :) 谢谢。错误指向第 64 行和第 124 行,你能告诉我这些行是哪几行吗? PS。您似乎已将代码发布为答案而不是编辑原始帖子,因此我已经编辑了您的帖子以供您包含它,它只是在等待同行评审。 另外请提供您收到的 JSON 示例 在为您提供 JSON 的同时,我插入了一行:print(decoded respose);在最终decodedResponse = json.decode(response.body); .我发现我超过了 1 的每日响应限制。这是谷歌最近设置的。 . .. . 【参考方案1】:

在为您提供 JSON 的同时,我插入了一行:print(decoded respose); 在最终decodedResponse = json.decode(response.body); .

我发现我已经超过了 1 的每日响应限制。这是谷歌最近设置的。 . .. .

这是错误信息:

flutter: error_message: 您已超出此 API 的每日请求配额。如果您没有设置自定义每日请求配额,请验证您的项目有一个有效的结算帐户:http://g.co/dev/maps-no-account,结果:[],状态:OVER_QUERY_LIMIT

再次感谢您的宝贵时间。干杯

【讨论】:

以上是关于Flutter / dart异常地理定位错误的主要内容,如果未能解决你的问题,请参考以下文章

ionic2:浏览器中的地理定位失败并出现错误:异常:未捕获(承诺中):错误

Max Mind 地理定位异常

W3C 地理定位 API 没有错误 没有期望也没有结果

Fluter:使用地理定位包的getPermission函数中的位置参数过多

如何让 Flutter 应用程序在锁定/睡眠屏幕上运行(地理定位器和计时器生成器)?

当我尝试使用地理编码器获取地址时,给出“未处理的异常:PlatformException(失败,失败,null)”的运行时错误