Now Reading: How to apply Repository Pattern in Flutter example with jsonplaceholder API

Loading

How to apply Repository Pattern in Flutter example with jsonplaceholder API

svgFebruary 23, 2023DartFlutterCodeStackGuide

To apply the repository pattern in a Flutter app that uses the jsonplaceholder API, you can follow these steps:

  1. Define the model: Create a model class that represents the data you’ll be working with. For example, if you’re using the jsonplaceholder API to retrieve posts, you could create a Post class with properties like id, title, and body.
class Post {
  final int id;
  final String title;
  final String body;

  Post({required this.id, required this.title, required this.body});
}
  1. Create the repository: Create a repository class that encapsulates the logic for retrieving data from the API. The repository should have a method for each operation you need to perform (e.g. getPosts, getPostById, etc.). These methods should return Future objects that resolve to the appropriate data types.
import 'package:http/http.dart' as http;
import 'dart:convert';

class PostRepository {
  final String apiUrl = "https://jsonplaceholder.typicode.com/posts";

  Future<List<Post>> getPosts() async {
    var response = await http.get(Uri.parse(apiUrl));
    if (response.statusCode == 200) {
      List<dynamic> body = json.decode(response.body);
      List<Post> posts = body.map((post) => Post.fromJson(post)).toList();
      return posts;
    } else {
      throw "Failed to get posts";
    }
  }

  Future<Post> getPostById(int id) async {
    var response = await http.get(Uri.parse('$apiUrl/$id'));
    if (response.statusCode == 200) {
      dynamic body = json.decode(response.body);
      Post post = Post.fromJson(body);
      return post;
    } else {
      throw "Failed to get post";
    }
  }
}

Note that the PostRepository class makes use of the http package to make HTTP requests to the jsonplaceholder API.

  1. Use the repository in your app: Finally, you can use the repository in your app to retrieve data from the API. For example, you could create a PostList widget that displays a list of posts:
class PostList extends StatefulWidget {
  @override
  _PostListState createState() => _PostListState();
}

class _PostListState extends State<PostList> {
  late Future<List<Post>> _postsFuture;

  @override
  void initState() {
    super.initState();
    _postsFuture = PostRepository().getPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Posts'),
      ),
      body: FutureBuilder<List<Post>>(
        future: _postsFuture,
        builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (BuildContext context, int index) {
                  Post post = snapshot.data![index];
                  return ListTile(
                    title: Text(post.title),
                    subtitle: Text(post.body),
                  );
                },
              );
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }
          }
          return Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

In this example, the PostList widget uses the PostRepository to retrieve a list of posts, and displays them in a ListView. The FutureBuilder widget is used to handle the asynchronous loading of data from the API.

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 apply Repository Pattern in Flutter example with jsonplaceholder API