Skip to content

Uuttssaavv/flutter-clean-architecture-riverpod

Repository files navigation

Coverage HitCount

Flutter Clean Architecture with Riverpod

A Flutter app that uses the "Dummy Json" api.

Features

  • Login
  • Fetch products
  • Search products
  • Pagination

What is used in this project?

  • Riverpod Used for state management

  • Freezed Code generation

  • Dartz Functional Programming Either<Left,Right>

  • Auto Route Navigation package that uses code generation to simplify route setup

  • Dio Http client for dart. Supports interceptors and global configurations

  • Shared Preferences Persistent storage for simple data

  • Flutter and Dart And obviously flutter and dart πŸ˜…

Project Description

Data

The data layer is the outermost layer of the application and is responsible for communicating with the server-side or a local database and data management logic. It also contains repository implementations.

a. Data Source

Describes the process of acquiring and updating the data. Consist of remote and local Data Sources. Remote Data Source will perform HTTP requests on the API. At the same time, local Data sources will cache or persist data.

b. Repository

The bridge between the Data layer and the Domain layer. Actual implementations of the repositories in the Domain layer. Repositories are responsible for coordinating data from the different Data Sources.

Domain

The domain layer is responsible for all the business logic. It is written purely in Dart without flutter elements because the domain should only be concerned with the business logic of the application, not with the implementation details.

a. Providers

Describes the logic processing required for the application. Communicates directly with the repositories.

b. Repositories

Abstract classes that define the expected functionality of outer layers.

Presentation

The presentation layer is the most framework-dependent layer. It is responsible for all the UI and handling the events in the UI. It does not contain any business logic.

a. Widget (Screens/Views)

Widgets notify the events and listen to the states emitted from the StateNotifierProvider.

b. Providers

Describes the logic processing required for the presentation. Communicates directly with the Providers from the domain layer.

Project Description

  • main.dart file has services initialization code and wraps the root MyApp with a ProviderScope
  • main/app.dart has the root MaterialApp and initializes AppRouter to handle the route throughout the application.
  • services abstract app-level services with their implementations.
  • The shared folder contains code shared across features
    • theme contains general styles (colors, themes & text styles)
    • model contains all the Data models needed in the application.
    • http is implemented with Dio.
    • storage is implemented with SharedPreferences.
    • Service locator pattern and Riverpod are used to abstract services when used in other layers.

For example:

final storageServiceProvider = Provider((ref) {
  return SharedPrefsService();
});

// Usage:
// ref.watch(storageServiceProvider);
  • The features folder: the repository pattern is used to decouple logic required to access data sources from the domain layer. For example, the DashboardRepository abstracts and centralizes the various functionality required to fetch the Product from the remote.
abstract class DashboardRepository {
  Future<Either<AppException, PaginatedResponse>> fetchProducts({required int skip});

  Future<Either<AppException, PaginatedResponse>> searchProducts({required int skip, required String query});
}

The repository implementation with the DashboardDatasource:

class DashboardRepositoryImpl extends DashboardRepository {
  final DashboardDatasource dashboardDatasource;
  DashboardRepositoryImpl(this.dashboardDatasource);

  @override
  Future<Either<AppException, PaginatedResponse>> fetchProducts(
      {required int skip}) {
    return dashboardDatasource.fetchPaginatedProducts(skip: skip);
  }

  @override
  Future<Either<AppException, PaginatedResponse>> searchProducts(
      {required int skip, required String query}) {
    return dashboardDatasource.searchPaginatedProducts(
        skip: skip, query: query);
  }
}

Using Riverpod Provider to access this implementation:

final dashboardRepositoryProvider = Provider<DashboardRepository>((ref) {
  final datasource = ref.watch(dashboardDatasourceProvider(networkService));

  return DashboardRepositoryImpl(datasource);
});

And finally accessing the repository implementation from the Presentation layer using a Riverpod StateNotifierProvider:

final dashboardNotifierProvider =
    StateNotifierProvider<DashboardNotifier, DashboardState>((ref) {
  final repository = ref.watch(dashboardRepositoryProvider);
  return DashboardNotifier(repository)..fetchProducts();
});

Notice how the abstract NetworkService is accessed from the repository implementation and then the abstract DashboardRepository is accessed from the DashboardNotifier and how each of these layers acheive separation and scalability by providing the ability to switch implementation and make changes and/or test each layer seaparately.

Testing

The test folder mirrors the lib folder in addition to some test utilities.

state_notifier_test is used to test the StateNotifier and mock Notifier.

mocktail is used to mock dependecies.

1. Testing the simple Provider provider:

test('dashboardDatasourceProvider is a DashboardDatasource', () {
    dashboardDataSource = providerContainer.read
    (dashboardDatasourceProvider(networkService));

    expect(
      dashboardDataSource,
      isA<DashboardDatasource>(),
    );
  });

And here is how we can test it separately from Flutter:

void main() {
  late DashboardDatasource dashboardDatasource;
  late DashboardRepository dashboardRepository;
  setUpAll(() {
    dashboardDatasource = MockRemoteDatasource();
    dashboardRepository = DashboardRepositoryImpl(dashboardDatasource);
  });
  test(
    'Should return AppException on failure',
    () async {
      // arrange
      when(() => dashboardDatasource.searchPaginatedProducts(skip: any(named: 'skip'), query: any(named: 'query')))
          .thenAnswer(
        (_) async => Left(ktestAppException),
      );

      // assert
      final response = await dashboardRepository.searchProducts(skip: 1, query: '');

      // act
      expect(response.isLeft(), true);
    },
  );
}

class MockRemoteDatasource extends Mock implements DashboardRemoteDatasource {}

To explore test coverage

run bash gencov.sh

Folder Structure

lib
β”œβ”€β”€ configs
β”‚ └── app_configs.dart
β”‚
β”œβ”€β”€ main
β”‚ β”œβ”€β”€ app.dart
β”‚ β”œβ”€β”€ app_env.dart
β”‚ β”œβ”€β”€ main_dev.dart
β”‚ β”œβ”€β”€ main_staging.dart
β”‚ └── observers.dart
β”‚
β”œβ”€β”€  configs
β”‚ └── app_configs.dart
β”œβ”€β”€ routes
β”‚ β”œβ”€β”€ app_route.dart
β”‚ └── app_route.gr.dart
β”‚
β”œβ”€β”€ services
β”‚ └── user_cache_service
β”‚   β”œβ”€β”€ data
β”‚   β”‚ β”œβ”€β”€ datasource
β”‚   β”‚ β”‚ └── user_local_datasource.dart
β”‚   β”‚ └── repositories
β”‚   β”‚  └── user_repository_impl.dart
β”‚   β”œβ”€β”€ domain
β”‚   β”‚ β”œβ”€β”€ providers
β”‚   β”‚ β”‚ └── user_cache_provider.dart
β”‚   β”‚ └── repositories
β”‚   β”‚   └── user_cache_repository.dart
β”‚   └── presentation
β”‚
β”œβ”€β”€ shared
β”‚ β”œβ”€β”€ data
β”‚ β”‚ β”œβ”€β”€ local
β”‚ β”‚ β”‚ β”œβ”€β”€ shared_prefs_storage_service.dart
β”‚ β”‚ β”‚ └── storage_service.dart
β”‚ β”‚ └── remote
β”‚ β”‚   β”œβ”€β”€ dio_network_service.dart
β”‚ β”‚   β”œβ”€β”€ network_service.dart
β”‚ β”‚   └── remote.dart
β”‚ β”œβ”€β”€ domain
β”‚ β”‚ β”œβ”€β”€ models
β”‚ β”‚ β”‚ β”œβ”€β”€ product
β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ product_model.dart
β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ product_model.freezed.dart
β”‚ β”‚ β”‚ β”‚ └── product_model.g.dart
β”‚ β”‚ β”‚ β”œβ”€β”€ user
β”‚ β”‚ β”‚ β”‚ └── user_model.dart
β”‚ β”‚ β”‚ β”œβ”€β”€ models.dart
β”‚ β”‚ β”‚ β”œβ”€β”€ paginated_response.dart
β”‚ β”‚ β”‚ β”œβ”€β”€ parse_response.dart
β”‚ β”‚ β”‚ └── response.dart
β”‚ β”‚ └── providers
β”‚ β”‚   β”œβ”€β”€ dio_network_service_provider.dart
β”‚ β”‚   └── sharedpreferences_storage_service_provider.dart
β”‚ β”œβ”€β”€ exceptions
β”‚ β”‚ └── http_exception.dart
β”‚ β”œβ”€β”€ mixins
β”‚ β”‚ └── exception_handler_mixin.dart
β”‚ β”œβ”€β”€ theme
β”‚ β”‚ β”œβ”€β”€ app_colors.dart
β”‚ β”‚ β”œβ”€β”€ app_theme.dart
β”‚ β”‚ β”œβ”€β”€ test_styles.dart
β”‚ β”‚ └── text_theme.dart
β”‚ β”œβ”€β”€ widgets
β”‚ β”‚ β”œβ”€β”€ app_error.dart
β”‚ β”‚ └── app_loading.dart
β”‚ └── globals.dart
β”‚
β”œβ”€β”€  features
β”‚ β”œβ”€β”€  authentication
β”‚ β”‚ β”œβ”€β”€  data
β”‚ β”‚ β”‚ β”œβ”€β”€  datasource
β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€  auth_local_data_source.dart
β”‚ β”‚ β”‚ β”‚ └── auth_remote_data_source.dart
β”‚ β”‚ β”‚ └── repositories
β”‚ β”‚ β”‚   └── atuhentication_repository_impl.dart
β”‚ β”‚ β”œβ”€β”€  domain
β”‚ β”‚ β”‚ β”œβ”€β”€  providers
β”‚ β”‚ β”‚ β”‚ └── login_provider.dart
β”‚ β”‚ β”‚ └── repositories
β”‚ β”‚ β”‚   └── auth_repository.dart
β”‚ β”‚ └── presentation
β”‚ β”‚   β”œβ”€β”€  providers
β”‚ β”‚   β”‚ β”œβ”€β”€  state
β”‚ β”‚   β”‚ β”‚ β”œβ”€β”€  auth_notifier.dart
β”‚ β”‚   β”‚ β”‚ β”œβ”€β”€  auth_state.dart
β”‚ β”‚   β”‚ β”‚ └──  auth_state.freezed.dart
β”‚ β”‚   β”‚ └── auth_providers.dart
β”‚ β”‚   β”œβ”€β”€  screens
β”‚ β”‚   β”‚ └── login_screen.dart
β”‚ β”‚   └── widgets
β”‚ β”‚     β”œβ”€β”€  auth_field.dart
β”‚ β”‚     └── button.dart
β”‚ β”œβ”€β”€  dashboard
....

Run this project

Clone this repository

git clone https://github.com/Uuttssaavv/flutter-clean-architecture-riverpod

Go to the project directory

cd flutter-clean-architecture-riverpod

Get all the packages

flutter pub get

Run the build runner command

flutter pub run build_runner build

Run the project

flutter run or simply press F5 key if you are using VSCode

About Me

Do visit my portfolio site or connect with me on linkedin