Flutter - Openweathermap api 调用错误 - 将参数传递给 api 调用不起作用

在看

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);
    }
  }
}

Loading_screen 类

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();
  }
}
米顿议员

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';

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章