简体   繁体   中英

FutureBuilder not completing after successful API call

I am attempting to have a widget which displays a Circular Progress Indicator until an API call inside a Future completes, and then shows a ListView.Builder Widget. Here is my code:

class LeadsList extends StatelessWidget {
  LeadsList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: post(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.hasData) {
            var liststring = snapshot.data;
            var list = jsonDecode(liststring!);
            return ListView.builder(
                itemCount: list["response"]?.length,
                itemBuilder: (context, index) {
                  return Card(
                      child: Text(list!["response"][index]["fullname"]));
                });
          } else {
            return const CircularProgressIndicator();
          }
        });
  }
}

Future<http.Response> post() {
  return http.post(Uri.parse('https://api_url.link'),
      body: jsonEncode({
        //json paramaters for API call
      }));
}

I am 99% sure the API call is being completed fine, as a. the same call works fine in a separate file where it is just being printed and not sent to a future builder, and b. the API backend logs show that the data is being retrieved fine, so my guess is that I'm not sending the results to the future builder in some way? any help would be greatly appreciated:)

Convert the method to async and await for result

Future<http.Response> post() async {
  return await http.post(Uri.parse('https://api_url.link'),
      body: jsonEncode({
        //json paramaters for API call
      }));
}

You are decoding Response class. The Response class provides a body parameter which has to be decoded.

Change one line.

var liststring = snapshot.data.body;

You can benefit from Dart typed nature by making FutureBuilder statically typed by adding the type of returning value.

return FutureBuilder<http.Response>(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM