Here is my code:
@override
void initState() {
super.initState();
weatherFuture = _getWeather();
}
@override
Widget build(BuildContext context) {
double viewBoxWidth = MediaQuery.of(context).size.width;
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FutureBuilder(
future: weatherFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Container(
width: viewBoxWidth * 0.35,
color: Colors.orange, // Todo: Remove this color later
child: WeatherTileColumn(
topTileDisplayText: snapshot.data.areaName,
bottomTileDisplayText: snapshot.data.weatherDescription,
topTileIcon: '',
bottomTileIcon:
_getWeatherIcon(snapshot.data.weatherConditionCode),
),
);
} else {
return Text(
'Loading Data...',
style: TextStyle(fontFamily: 'Merriweather', fontSize: 15),
textAlign: TextAlign.center,
);
}
}),
Container(
width: viewBoxWidth * 0.2,
margin: EdgeInsets.only(top: 95),
child: TextButton(
child: Icon(
Icons.refresh,
color: Colors.black87,
size: 55,
),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.transparent)),
onPressed: () {
setState(() {
weatherFuture = _getWeather();
});
},
),
),
FutureBuilder(
future: weatherFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Container(
width: viewBoxWidth * 0.35,
color: Colors.purple,
child: WeatherTileColumn(
topTileDisplayText: snapshot.data.temperature.toString(),
bottomTileDisplayText:
snapshot.data.tempFeelsLike.toString(),
topTileIcon: '',
bottomTileIcon: '️',
),
);
} else {
return Text(
'Loading Data...',
style: TextStyle(fontFamily: 'Merriweather', fontSize: 15),
textAlign: TextAlign.center,
);
}
},
)
],
),
);
In this code, if you look at the main widgets inside the children of the Row widget, you will see that there are two FutureBuilder widgets and a Container widget.
What has to happen is upon pressing that TextButton inside the Container, I want the two future builder widgets to be re updated with newly fetched data.
My current attempt was to do:
setState() {
weatherFuture = _getWeather();
}
inside the callback function for the onPressed
method. And it does not work. I looked at many solutions and articles and could not get this to work.
(Also I checked Reload data when using FutureBuilder stack overflow post and this is not a duplicate. In that post, the button that rebuilds the FutureBuilder widget is inside the FutureBuilder widget but in this case it isn't. So that solution did not work for me.)