I am building a Flutter app where I fetch data from an API inside the initState() method. However, the API data does not display on the first run — it only appears after I perform a hot reload.
class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
String _apiData = "";
@override
void initState() {
super.initState();
fetchData();
}
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
setState(() {
_apiData = response.body;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(_apiData.isEmpty ? "Loading..." : _apiData),
),
);
}
}
Problem:
- On first app load, the screen only shows "Loading...".
- After a hot reload (in VSCode or Android Studio), the API data shows correctly.
- It seems like setState is not updating the UI properly on first load.
What I tried:
- Checked API response manually — it's working.
- Verified that setState() is called after API fetch.
- Added print statements — they show data is retrieved.
- Tried moving the API call to build() method (still no success).
How can I ensure that API data is loaded and displayed properly on the initial load, without needing a hot reload?
getUserName
provides the name to the widget? I see a variablemData
but you don't show how you fill it.