Home > Back-end >  OpenWeatherMap Invalid API Key in Flutter
OpenWeatherMap Invalid API Key in Flutter

Time:06-17

Here, I am trying to make an API call to OpenWeatherMap. When I do flutter run, it prints 401 which is code for Invalid API Key, although I have generated the API Key in an appropriate way and it is active and copied correctly.

This is the main.dart:

import 'package:flutter/material.dart';
import 'package:clima/screens/loading_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: LoadingScreen(),
    );
  }
}

This is the loading_screen.dart:

import 'dart:convert';
import '../services/location.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

const APIKey = '69f9afe03f52ef5c83887fc86dd79d99';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  double? latitude;
  double? longitude;

  void initState() {
    super.initState();
    getLocation();
  }

  void getLocation() async {
    Location l = Location();
    await l.getCurrentLocation();
    l.latitude = latitude;
    l.longitude = longitude;
    getData();
  }

  void getData() async {
    http.Response response = await http.get(Uri.parse('https://api.openweathermap.org/data/3.0/onecall?lat=$latitude&lon=$longitude&appid=$APIKey'));
    if (response.statusCode == 200) {
      String data = response.body;
      var decodedData = jsonDecode(data);
      print(decodedData);
    } else {
      print(
        response.statusCode,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}

This is the location.dart:

import 'package:geolocator/geolocator.dart';

class Location {
  double? latitude;
  double? longitude;

  Future getCurrentLocation() async {
    try {
      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.low,
      );
      latitude = position.latitude;
      longitude = position.longitude;
    } catch (e) {
      print(e);
    }
  }
}

What could possibly be the problem here, and how do I fix this?

CodePudding user response:

checkout Using OpenWeatherMap API gives 401 error here you will find some reasons why your apikey is not working. also, it takes 2 hours for key activation.

CodePudding user response:

Go to the website and generate new api key by deleting the previous one.

You can generate as many api keys as required.

  • Related