Flutter - Ошибка вызова API Openweathermap - Передача параметра в вызов API не работает - PullRequest
0 голосов
/ 29 марта 2020

Класс местоположения отвечает за получение долготы и широты. Метод getData () из класса Loading_screen отвечает за вызов API для получения данных о погоде. Проблема в том, что когда я передаю значения долготы и широты в URL-адрес API, он возвращает ошибку 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();
  }
}

Ответы [ 2 ]

1 голос
/ 29 марта 2020
1 голос
/ 29 марта 2020

В вашем 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';
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...