I have a program that reads API data. It shows the information in the program in a list.
But I have a problem:
When I run the program, the information is not loaded at the beginning of the program! I must refresh or save the page to load the information.
Please guide me how I can load and display the information at the start of the complete execution.
My program code is as follows:
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
static List<Place> placeList = [];
static PelakNetwork networkObject = PelakNetwork();
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
void initState() {
apiCall();
setState(() {});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: backgroundColor,
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(defaultPadding),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
SizedBox(
height: 120,
width: double.infinity,
child: Category_List_home_widget(),
),
MyTextWidget(
text: "جدیدترین ها",
),
SizedBox(
height: 10,
),
SizedBox(
height: 251,
width: double.infinity,
child: TopLocation_widget(),
),
SizedBox(
height: 10,
),
MyTextWidget(
text: 'جدید ترین ها',
),
SizedBox(
height: 10,
),
SizedBox(
height: 251,
width: double.infinity,
child: TopLocation_widget(),
),
SizedBox(
height: 40,
),
//! //////////////////////////////
newLocationWidget(),
],
),
),
),
);
}
}
void apiCall() async {
HomeScreen.placeList = await HomeScreen.networkObject.getData();
}
2
Answers
You have to verify if the call of the method apiCall() is correct, if it isn’t the problem come probably from here.
You can use Tests or Debug to verify it.
You cannot execute async operations in initState which is by necessity sync only.
You can start async operations, saving the Futures in your State, and then use something like FutureBuilder to show something before the futures are completed.
Also, minor nit, but your super.initState() must always go first before the rest of the override.