'successfully display json in flutter, but not showing on android screen
I've managed to display API data to flutter, but strangely it only appears in the debug console, but when hot reloaded, the data appears on the android screen.
Code
Widget build(BuildContext context) {
AuthProvider authProvider = Provider.of<AuthProvider>(context);
UserModel? user = authProvider.user;
JobsProvider? jobsProvider = Provider.of<JobsProvider>(context, listen: false);
jobsProvider.getJobs(user?.token);
Widget newArrival() {
return Container(
margin: const EdgeInsets.only(
top: 14,
),
child: Column(
children: jobsProvider.jobs
.map(
(jobs) => CardJob(),
)
.toList(),
),
);
}
After hot reload
Solution 1:[1]
The problem has to do with the fact that the request's function is probably async
.
Your code is not waiting for a response, instead it renders the page before the data is received.
Normally, you should add an await in front of the call, as: await jobsProvider.getJobs(user?.token);
(if that's the function). But you cannot call an async function into the build()
method. That's why you could use a FutureBuilder.
An example of the FutureBuilder that returns a String:
FutureBuilder<String>(
future: myFunction("param"),
builder:
(BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
final theText = snapshot.data
Text(theText ?? ""),
}
return const CircularProgressIndicator() //While awaiting show the loading indicator
},
),
Solution 2:[2]
If the screen is as you wanted after hot reload it means that when the screen is drawn your data was not available. You can try to call setState after receiving the jobs json or if you do this task with the initialization of the screen make sure that you init the page after the data arrives.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dani3le_ |
Solution 2 | Alperen Ekin |