Flutter fetch data from API and display in ListView

CodeWithFlutter
3 Min Read

Here’s an example of how to fetch data from an API and display it in a Flutter ListView:

Add the http package to your pubspec.yaml file:

dependencies:
  http: ^0.12.2

Import the http and dart:convert libraries in your Dart file:

import 'package:http/http.dart' as http;
import 'dart:convert';

Define a Future function to fetch the data from the API:

Future<List<dynamic>> fetchData() async {
  final response = await http.get('https://your-api-endpoint.com/data');

  if (response.statusCode == 200) {
    // If the API call was successful, parse the JSON response
    return json.decode(response.body);
  } else {
    // If the API call was unsuccessful, throw an error
    throw Exception('Failed to load data');
  }
}

In your StatefulWidget‘s build method, use a FutureBuilder to build the ListView:

@override
Widget build(BuildContext context) {
  return FutureBuilder<List<dynamic>>(
    future: fetchData(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        // If the API call was successful, build the ListView
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(snapshot.data[index]['title']),
              subtitle: Text(snapshot.data[index]['subtitle']),
            );
          },
        );
      } else if (snapshot.hasError) {
        // If the API call was unsuccessful, display an error message
        return Center(
          child: Text('${snapshot.error}'),
        );
      }

      // If the data is still being loaded, show a loading indicator
      return Center(
        child: CircularProgressIndicator(),
      );
    },
  );
}

In this example, the fetchData function uses the http.get method to make an HTTP GET request to the API endpoint. If the API call is successful, the response is parsed into a list of Dart objects using the json.decode method. If the API call is unsuccessful, an error is thrown.

The FutureBuilder widget takes the fetchData Future as an argument and listens for its completion. Depending on the state of the Future, it either displays the ListView, an error message, or a loading indicator. The ListView.builder method is used to build the list, with each item being represented by a ListTile.

Share this Article
Leave a comment