Home > other >  successfully display json in flutter, but not showing on android screen
successfully display json in flutter, but not showing on android screen

Time:05-13

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(),
        ),
      );
    }

Before hot reload enter image description here

enter image description here

After hot reload

enter image description here

CodePudding user response:

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
  },
),

CodePudding user response:

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.

  • Related