Location类负责获取经度和纬度。Loading_screen类的getData((方法负责调用api来获取天气数据。问题是,当我将经度和纬度值传递到api的url时,它返回错误400。解决方法是对经度和纬度进行硬编码,并成功检索到api数据。我不明白为什么将经度和纬度值传递给api调用不起作用
位置
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
class Location{
double longitude;
double latitude;
Future<void> getCurrentLocation() async{
try{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
longitude = position.longitude;
latitude = position.latitude;
print('Longitude: $longitude n' +
'Latitude: $latitude');
}catch(e){
print(e);
}
}
}
加载屏幕类
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:clima/location.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
var apiKey = 'secret';
double lat, lon;
@override
void initState() {
getLocation();
}
void getData() async{
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&${lon}&appid=$apiKey';
//var url = 'http://api.openweathermap.org/data/2.5/weather?lat=14.6102473&121.0043158&appid=secret';
//var url = 'http://api.openweathermap.org/data/2.5/weather?lat=14.6102473&lon=121.0043158&appid=secret';
var request = await http.get(url);
if(request.statusCode == 200){
String data = request.body.toString();
var city = jsonDecode(data)['name'];
var description = jsonDecode(data)['weather'][0]['description'];
print('Welcome to $city city!');
print('Weather: $description');
}else{
print(request.statusCode);
print('Latitude is: $lat *** Longitude is: $lon'); // this prints longitude and latitude values
print('request $url'); // when I entered the url in postman, I'm getting the same error 400
}
}
void getLocation() async{
Location location = new Location();
await location.getCurrentLocation();
lat = location.latitude;
lon = location.longitude;
getData();
}
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
您的url中缺少参数名称lon
。
代替:
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&${lon}&appid=$apiKey';
写入:
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=$apiKey';
更改它;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&${lon}&appid=$apiKey';
与此相关;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=$apiKey';