dart - Flutter / dart异常地理定位错误
问题描述
我对使用地理位置的颤振/飞镖有疑问。我已按照一门 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)
位置.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())
],
);
}
}
解决方案
在为您提供 JSON 时,我插入了一行: print(decoded respose); 最终decodedResponse = json.decode(response.body); .
我发现我超过了 1 的每日响应限制。这是谷歌最近设置的。. ...
这是错误消息:
颤振:{error_message:您已超出此 API 的每日请求配额。如果您没有设置自定义每日请求配额,请验证您的项目是否有一个有效的计费帐户:http ://g.co/dev/maps-no-account,结果:[],状态:OVER_QUERY_LIMIT}
再次感谢您的时间。干杯
推荐阅读
- python - 如何在 Python 中覆盖部分文本文件?
- javascript - 了解在 while 循环中使用真/假变量作为测试条件
- javascript - Google People API Javascript - 将 GivenName 存储为变量
- java - 如何在 JavaFX 中修复小字体的扭曲文本?
- c# - 在 asp.net 中使用 Protobuf-Net 序列化数据
- android - Android - Align different font-sizes on same baseline
- statistics - 如何比较来自不同方差分析的 r 平方?
- azure-cosmosdb - Getting single gremlin result from multiple paths
- visual-studio - MSBuild with Azure Devops and shared library
- php - Foreach array and create new array based on index then loop through that