Home > Software design >  Flutter : How can I get Value of a varibale from a Async method and pass it to Text Widget?
Flutter : How can I get Value of a varibale from a Async method and pass it to Text Widget?

Time:05-24

I want to show the user some weather data [temperature, condition, cityName]. I am getting the weather data(jsonDecoded) using an Asynchronous method. But I am unable to pass that data to the Text widget. I have tried this Way, but the Text widget shows Null in the emulator.

enter image description here

Here is my Code-

class _MyHomePageState extends State<MyHomePage> {

///want to pass this data to text Widget
var temperature;
var condition;
var cityName;

 initState() {
 LocationData();
}

var Longtitude;
var Latitude;

// By this method I am getting weatherData from another class
LocationData() async {
getlocation GetLocation = getlocation();
await GetLocation.determinePosition();

Latitude = GetLocation.Lattitude;
Longtitude = GetLocation.Longtitude;

NetworkHelper networkHelper = NetworkHelper(
    'https://api.openweathermap.org/data/2.5/weather? 
     lat=$Latitude&lon=$Longtitude&appid=$apiKey');

var weatherData = await networkHelper.getData();

temprature = weatherData['main']['temp'];
condition = weatherData['weather'][0]['id'];
cityName = weatherData['name'];

}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
         child: Column(
           mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Text(
                temprature.toString(),
                style: MyTextStyle,
                            ),
                Text(
                condition.toString(),
                style: MyTextStyle,
                            ),
                Text(
                cityName.toString(),
                style: MyTextStyle,
                            )
             ],
           ),
         ),
       ),
     );

     // TODO: implement build
     throw UnimplementedError();
  }
 }

CodePudding user response:

Try doing this after you've fetched the weatherData:

setState(() {
  temprature = weatherData['main']['temp'];
  condition = weatherData['weather'][0]['id'];
  cityName = weatherData['name'];
});

There are more things you will run into that won't be top-notch... I suggest that you e.g. checkout the FutureBuilder() widget and see how that could be used in your case.

CodePudding user response:

If in LocationData method if you're getting the correct value in temperature, condition and cityname then issue with you're not using setState there. As widget will not re-render until setState is used and thus variable displays old values there for temperature/condition.

Use setState in LocationData.

setState(() {
  temprature = weatherData['main']['temp'];
  condition = weatherData['weather'][0]['id'];
  cityName = weatherData['name'];
});
  • Related