Flutter #day32

ยท

2 min read

Getting back to my udemy flutter course....

So basically I am working on weather app, first thing which I did was to get the current location, For this I used geolocator package.

import 'package:geolocator/geolocator.dart';


// the below function is used to fetch the current location.
Future<void> getLocation() async {

// this part checks for the location permission
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission != LocationPermission.whileInUse &&
          permission != LocationPermission.always) {
        // Handle the scenario if the user denies location permission.
        return;
      }
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.low);
    print(position.longitude);
    print(position.latitude);
    getData(position.latitude, position.longitude);
  }

// this makes use of getCurrentposition of Geolocator which returns the longi
// tude and latitude.

now that with the help of geolocator we have our location we can use the weather stack api to get the weather of current location.

import 'package:http/http.dart' as http;
import 'dart:convert';

getData(position.latitude, position.longitude);

void getData(double latitude, double longitude) async {
    final apiKey = 'bf37ed037ee6f380172b8531dab4154f';
    final baseUrl = 'http://api.weatherstack.com/current';
    final query = '$latitude,$longitude';
    // this query thing is to point to a particular place of where you wanna fetch
    // the details for.

    final url = Uri.parse('$baseUrl?access_key=$apiKey&query=$query');
    // in the above line of code we are constructing an url to make the
    // http get request
    // The Uri.parse function is used to create a Uri object from the URL
    // string you've constructed. The Uri object provides helpful methods 
    // for working with URLs, such as encoding query parameters correctly.

    final response = await http.get(url);

    // In this line of code, you're using the http package to send an HTTP GET 
    // request to the URL you've constructed. The http.get function returns a 
    // Future<http.Response>, and by using the await keyword, 
    // you're waiting for the response to come back.

    if (response.statusCode == 200) {
      // final data = response.body;

      Map<String, dynamic> weatherData = json.decode(response.body);

      // final data = response.body;

      // Process the 'data' here (e.g., parse JSON or perform other operations).
      print(weatherData);
    } else {
      print('Request failed with status: ${response.statusCode}');
    }
  }

implemented the functionalities, and now my app is kinda ready, I have a loading screen and then a location screen.

ย