Repository Pattern in Flutter: Enhancing App’s Architecture

Repository Pattern in Flutter: Enhancing App’s Architecture

Quick Summary: Enhance your Flutter app's architecture with the Repository Pattern, a key to clean and maintainable code. This article delves into its implementation, illustrating how it separates data access logic from the business logic, leading to more modular, scalable, and testable applications.

Introduction

The Repository Pattern is a design pattern that separates the logic that retrieves data from different sources (such as a network call, local database, or cache) from the rest of the application. In the context of Flutter and Dart, this pattern can be useful for managing data retrieval and providing a clean API for the rest of your application.

Hire Flutter Developers

Here's a simple example of implementing the Repository Pattern in Flutter for network calls:

Create a data model (Post.dart):

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

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

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



Create a repository interface (post_repository.dart):

import 'dart:async';

abstract class PostRepository {
  Future<List<Post>> fetchPosts();
}


Implement the repository with a network data source (post_repository_impl.dart):

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

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

  @override
  Future<List<Post>> fetchPosts() async {
    final response = await http.get(Uri.parse(apiUrl));

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

 

Use the repository in your Flutter application (main.dart):

import 'package:flutter/material.dart';

import 'post_repository.dart'<