API call returning delayed data

Asked

Viewed 49 times

0

What’s wrong with my function? Because, the data called in the second api returns with enough delay.

How do I load the screen only after the return of the second API?

var os = new List<OS>();

  _getOs() {
    API.getOS().then((response) {
      setState(() {
        Map<String, dynamic> data = json.decode(response.body);

        os = List<OS>.from(data['registros'].map((x) => OS.fromJson(x)));

        for (var i = 0; i < os.length; i++) {
          API.getCliente(os[i].idCliente).then((response) {
            var clies = new List<Cliente>();

            Map<String, dynamic> dataCli = json.decode(response.body);
            clies = List<Cliente>.from(
                dataCli['registros'].map((x) => Cliente.fromJson(x)));

            os[i].nomeCliente = clies[0].fantasia;
          });
        }
      });
    });
  }

1 answer

2

To load the part of the layout you want, after the API calls there are a few ways, I will give you the example of one and then you try to apply for your case (Since you have not given us much information).

You can use the FutureBuilder, that when building the layout it will wait for the API to return some value and then build what it needs.

To have the expected result, using the FutureBuilder, it is necessary to use the await instead of then()

class MyWidget extends StatelessWidget {
  
   Future<List<OS>> _getOs() async {
     var os = new List<OS>();
     final responseOS = await API.getOS();
     
     Map<String, dynamic> data = json.decode(responseOS.body);

     setState(() {
       os = List<OS>.from(data['registros'].map((x) => OS.fromJson(x)));
     });

     for (var i = 0; i < os.length; i++) {
       final responseCliente = await API.getCliente(os[i].idCliente);
       var clies = new List<Cliente>();

       Map<String, dynamic> dataCli = json.decode(responseCliente.body);
       clies = List<Cliente>.from(
       dataCli['registros'].map((x) => Cliente.fromJson(x)));

       os[i].nomeCliente = clies[0].fantasia;
     }
     
     return os;
  }
  
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _getOs(),
      builder: (context, AsyncSnapshot<List<OS>> snapshot) {
        //Enquanto não existir nenhum valor retornado
        if (!snapshot.hasData)
          return Center(child: Text("Carregando dados"));

        // Quando existir dados a serem exibidos
        return Container(
          // child: Coloque aqui dentro sua estrutura atual, utilize a propriedade snapshot[n] para pegar os itens da lista retornada.
        );
      },
    );
  }
}

Note: I do not have access to Flutter at the moment, there may be some problems in the code.

You can read more about here Futurebuilder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.