Now Reading: How to Paginate REST API in Flutter

Loading

How to Paginate REST API in Flutter

svgFebruary 8, 2023FlutterCodeStackGuide

In Flutter, you can paginate REST API results by sending page numbers and page sizes as parameters with each request and retrieve a limited number of records per request. Here’s an example of how you can implement pagination in a Flutter application.

Here’s an example of how we can implement pagination in a Flutter application using the https://jsonplaceholder.typicode.com/posts API:

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({this.userId, this.id, this.title, this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }
}

First, define a method that makes the API request, passing the page number and page size as parameters:

  1. First, define a method that makes the API request, passing the page number and page size as parameters:
Future<List<Post>> getPosts(int page, int pageSize) async {
  final response = await http.get(
      'https://jsonplaceholder.typicode.com/posts?_page=$page&_limit=$pageSize');

  if (response.statusCode == 200) {
    var posts = (json.decode(response.body) as List)
        .map((p) => Post.fromJson(p))
        .toList();
    return posts;
  } else {
    throw Exception('Failed to load posts');
  }
}

In your widget, initialize the variables for the current page number and page size:

  1. Then, in the build method, make the API call using the getPosts method and update the UI accordingly:
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: FutureBuilder<List<Post>>(
      future: getPosts(_currentPage, _pageSize),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return ListView.builder(
            itemCount: snapshot.data.length + 1,
            itemBuilder: (context, index) {
              if (index == snapshot.data.length) {
                return Container(
                  padding: EdgeInsets.all(10.0),
                  child: RaisedButton(
                    child: Text('Load more'),
                    onPressed: () {
                      setState(() {
                        _currentPage++;
                      });
                    },
                  ),
                );
              }
              // Show the post items
              return ListTile(
                title: Text(snapshot.data[index].title),
                subtitle: Text(snapshot.data[index].body),
              );
            },
          );
        } else if (snapshot.hasError) {
          return Text("${snapshot.error}");
        }
        return CircularProgressIndicator();
      },
    ),
  );
}

This is just a simple example, you may need to make adjustments based on your API structure and requirements.

0 People voted this article. 0 Upvotes - 0 Downvotes.
svg

What do you think?

Show comments / Leave a comment

Leave a reply

svg
Quick Navigation
  • 01

    How to Paginate REST API in Flutter