Home > Enterprise >  My values are being loaded only after hot reloading
My values are being loaded only after hot reloading

Time:10-15

I have been working on a weather app that displays live weather data. I am relatively new to flutter and dart.

When I run the code, the app builds and instead of showing the three values on the screen, all three values are displayed as null. But when I hot reload, the values appear. Anyone?

import 'dart:convert';
import 'package:flutter/material.dart';
import 'Services/LocationServices.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  var Longitude;
  var Latitude;
  var CityName;
  var Temperature;
  var Description;
  var appid = '111267e28d8012bc99ae1aa67bb9d87f';

  void getLocation() async{
    Location location = Location();
    await location.getCurrentLocation();

    Latitude = location.latitude;
    Longitude = location.longitude;
    print('Latitude = ${location.latitude}');
    print('Longitude = ${location.longitude}');
    getData();

  }

  void getData() async{
    var url = Uri.parse('https://api.openweathermap.org/data/2.5/weather?lat=$Latitude&lon=$Longitude&appid=$appid&units=metric');
    http.Response response = await http.get(url);

    if (response.statusCode == 200){
      String Data = response.body;
      var city = jsonDecode(Data)['name'];
      CityName = city;
      var temp = jsonDecode(Data)['main']['temp'];
      Temperature = temp;
      var condition = jsonDecode(Data)['weather'][0]['description'];
      Description = condition;

      // print('City = $city');
      // print('Temperature = $temp');
      // print('Description = $condition');

    }else{
      print(response.statusCode);
    }
  }

  @override
  void initState() {
    super.initState();
    getLocation();

  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(child: Text('$CityName')),
            Center(child: Text('$Temperature')),
            Center(child: Text('$Description')),
            // Text('$temperature'),
            // Text('$temperature'),
            // Text('$temperature'),
          ],
        )
      ),
    );
  }
}

This is the LocationServices.dart file. Anyone have any ideas to what i did wrong here?

import 'package:geolocator/geolocator.dart';

class Location{

  var latitude;
  var longitude;

  Future<void> getCurrentLocation() async{

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

CodePudding user response:

You need to call setState to trigger a state change in a StatefulWidget

void getData() async {
  var url = Uri.parse(
      'https://api.openweathermap.org/data/2.5/weather?lat=$Latitude&lon=$Longitude&appid=$appid&units=metric');
  http.Response response = await http.get(url);

  if (response.statusCode == 200) {
    setState(() {
      String Data = response.body;
      var city = jsonDecode(Data)['name'];
      CityName = city;
      var temp = jsonDecode(Data)['main']['temp'];
      Temperature = temp;
      var condition = jsonDecode(Data)['weather'][0]['description'];
      Description = condition;
    });

    // print('City = $city');
    // print('Temperature = $temp');
    // print('Description = $condition');

  } else {
    print(response.statusCode);
  }
}

CodePudding user response:

Read about FutureBuilder! I think that will help you!

CodePudding user response:

Just a simple error call the methods in initState on top of the all the methods.

   @override
   void initState() {
   getLocation();
   getData();
   super.initState();
   }

Call this method before getLocation() method. It will automatically execute the getData() and getLocation() methods when you come to the page. So no need to refresh the page.

  • Related