Search code examples
apiflutterdartflutter-webopenweathermap

Unable to Fetch Data from Open Weather API in Flutter


My Result

enter image description here

Source Code

Loading Screen

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

Get CurrentLocation Method

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) {

    }
  }
}

I want this result(https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22) but unable to get this. Can you please tell me where I am wrong


Solution

  • You have to add the https:// to your url. like this:

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

    Also, please always post your code in text, not images.