【问题标题】:Unable to Fetch Data from Open Weather API in Flutter无法从 Flutter 中的 Open Weather API 获取数据
【发布时间】:2021-06-20 10:27:29
【问题描述】:

我的结果

源代码

载入画面

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:clima/services/location.dart';
import 'package:http/http.dart'as http;
class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }
  @override
  void getlocation()async{
    Location location=Location();
   await location.getcurrentlocation();
   print(location.lat);
   print(location.long);
  }
  void getdata()async{
    http.Response response = await http.get(Uri.parse
      ('samples.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml&appid=b6907d289e10d714a6e88b30761fae22')
    );
    if (response.statusCode == 200) {
      String data = response.body;
      print(data);
    } else {
      print(response.statusCode);
    }}
  Widget build(BuildContext context) {
    getlocation();
    getdata();
    return Scaffold(
    );
  }
}

获取当前位置方法

import 'package:geolocator/geolocator.dart';
class Location{
  double long;
  double  lat;
  Future<void> getcurrentlocation() async {
    try {
      Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
      lat = position.latitude;
      long= position.longitude;
    } catch (e) {

    }
  }
}

我想要这个结果(https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22) 但无法得到这个。你能告诉我我哪里错了

【问题讨论】:

    标签: api flutter dart flutter-web openweathermap


    【解决方案1】:

    您必须将https:// 添加到您的网址。 像这样:

    Uri.parse('https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22');
    

    另外,请始终以文本而不是图片的形式发布您的代码。

    【讨论】:

    • https:// 不起作用。它显示错误“XML Http Request error”
    • 你是在 Flutter web 上运行这个吗?
    • 是的,我正在网络上运行它
    • 您需要在帖子中提及这一点,这与 CORS 有关,因为 API 不允许跨内容源内容。通过将 https 添加到您的 Uri,您的问题开始得到解决。第二个问题不同。我怀疑您当前正在使用任何 .htacces 文件或运行模拟服务器。在 Chrome 上禁用 CORS 策略是一种临时解决方案。如果你在手机上运行它,它会工作。阅读有关 CORS 和新错误的更多信息。如果这有助于您将其标记为答案。编码愉快。
    • 非常感谢您
    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 2020-02-27
    • 2019-08-26
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2020-11-16
    相关资源
    最近更新 更多