Flutter implementation of 4+2 Layered Architecture

Overview

A Flutter implementation of 4+2 Layered Architecture structure.

This is an implementation of the architecture described in 4+2 Layered Architecture and its companion publication 4+2 Layered Architecture - A Flutter Implementation.

  • Provides the project structure with all suggested layers, each in a separate package.
  • Implements a simple domain in a runnable sample application.
  • Two Flutter dependencies are notable for this implementation:

Architecture overview:

Project Structure

The 4+2 Layered Architecture describes the importance of Separation of Concerns in software development. When applying to project architecture I structured the application with:

  • 4 Major Layers:
    • Domain Layer (business rules)
    • Data Layer (persistence)
    • Service Layer (external services)
    • Presentation Layer (UI)
  • 2 Accessory Layers:
    • Core Layer (shared library)
    • Dependency Injection Layer (dependency inversion)

Layer objects

A key implementation in this proposal is the use of an AppLayer object for each structured layer, the configuration of each layer and the interaction between layers are responsibilities of these objects. Initialization is orchestrated by Dependency Injection's layer object.

The DILayer object is initialized in the main method, and inside this call DILayer object fetchs and initializes all other layer objects. Then it configures the DomainLayer object with all required dependencies (interface implementations) retrieved from provider layers (DataLayer and ServiceLayer objects).

Once more, the driving force behind the use of these layer objects is Separation of Concerns: no layer needs to know about the internal implementations of any other layer.


Project structure:

Project Structure

All code is separated in layers, each layer organized as a separate internal package.
This separation of concerns makes inter layer dependencies explicity and tests modular.

The main project structure, shown in the following image, has:

  • flutter project files: pubspec.yaml, build**, etc
  • lib folder with main.dart
  • packages folder containing all layers:
    • _core_layer
    • _data_layer
    • _di_layer
    • _domain_layer
    • _service_layer
    • _presentation_layer
  • test folder for main project

Each layer folder has its own package structure with:

  • pubspec.yaml
  • test folder for that layer

Main project and outer layers pubspec.yaml use path dependencies to refer to inner layers, for example, in _domain_layer's pubspec you see:

dependencies:
  _core_layer:
    path: ../_core_layer

In this structure image I show my VSCode Explorer using MultiRoot feature (aka Workspace files) setting each layer as a root folder.
I use this MultiRoot feature combined with Explorer Exclude extension to have a focused view for my projects.

The image shows just the Domain Layer open for exemplification.

Besides these files shown in the image there are a number of configuration files for flutter, VSCode, GIT and others. Since we are working with 6 extra internal packages we get a lot of these configuration files and code navigation on VSCode explorer becomes very clumsy. Thus the suggestion to use this Explorer Exclude extension.

Below my configuration for MuiltiRoot and Explorer Exclude worspace. This configuration is provided in this template at .vscode/layered_template.code-workspace file:

{
  "folders": [
    { "path": ".." },
    { "path": "../packages/_core_layer", "name": "Core Layer" },
    { "path": "../packages/_data_layer", "name": "Data Layer" },
    { "path": "../packages/_di_layer", "name": "DI Layer" },
    { "path": "../packages/_domain_layer", "name": "Domain Layer" },
    { "path": "../packages/_service_layer", "name": "Service Layer" },
    { "path": "../packages/_presentation_layer", "name": "Presentation Layer" }
  ],
  "settings": {
    "files.exclude": {
      "**/.git": true,
      "**/.svn": true,
      "**/.hg": true,
      "**/CVS": true,
      "**/.DS_Store": true,
      "**/Thumbs.db": true,
      "**/.dart_tool": true,
      "**/.idea": true,
      "**/.vscode": true,
      "**/*.iml": true,
      "**/.metadata": true,
      "**/.packages": true,
      "**/CHANGELOG.md": true,
      "**/LICENSE": true,
      "**/README.md": true,
      "**/analysis_options.yaml": true,
      "**/pubspec.lock": true,
      ".code-workspace": true,
      ".flutter-plugins": true,
      ".flutter-plugins-dependencies": true,
      ".gitignore": true,
      "android": true,
      "build": true,
      "packages": true
    },
    "explorerExclude.backup": null
  }
}

The sample domain:

This template defines a simple domain model with "in memory" temporary persistence.
Persistence is implemented using a StateNotifier to keep entities and notify storage state changes.
The purpose is not to implement a full featured application, but rather to provide a simple application with full layered architecture structure.


Using this template for a new Flutter project:

This a start up template for a layered architecture project.

  1. Click on Use this template on this template main page in github:

    https://github.com/cc-nogueira/flutter_layered_template/

  2. Clone your repository to your development machine:

   git clone https://github.com/your-repo/your-project.git
  1. Change name in pubspec.yaml
   name: your-project
  1. Run the provided utility project.dart that initializes the main project and all layer packages, creating configuration files that not stored in git (project and build files).
   cd <your-project>
   dart project.dart init
  1. Open Workspace from File
   Rename workspace file from .vscode/layered_template.code-workspace to <your-project>.code-workspace
   Open VSCode
   Choose "Open Workspace from File...: from the File menu
   Select <your-project>/.vscode/<your-project>.code-workspace

This provided project.dart utility has commands to init, clean and build the project and its internal packages.
You can always run commands in a specific package folfer using the terminal, for example you can run build_runner to generate json or freezed files in the domain layer folder. But when you want to run build_runner or clean for all layers you better running dart project.dart with the specific command.


References:

Publications:

Videos:

You might also like...

Flutter App Templete is a project that introduces an approach to architecture and project structure for developing Flutter apps.

Flutter App Template "Flutter App Template" is a project that introduces an approach to architecture and project structure for developing Flutter apps

Jan 5, 2023

Flutter mvvm archi - Flutter Advanced Course - Clean Architecture With MVVM

flutter_mvvm_archi A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you start

Jan 8, 2022

Starter-Flutter - Starter flutter project for best architecture and seperation of code

Starter-Flutter - Starter flutter project for best architecture and seperation of code

Modular-Architecture Codebase CodeBase , Infrastructure and the common Layers (c

Feb 16, 2022

🚀 Sample Flutter Clean Architecture on Rorty App focused on the scalability, testability and maintainability written in Dart, following best practices using Flutter.

🚀 Sample Flutter Clean Architecture on Rorty App focused on the scalability, testability and maintainability written in Dart, following best practices using Flutter.

Rorty Flutter Rorty 📺 (work-in-progress for V2 👷 🔧️ 👷‍♀️ ⛏ ) Getting Started Flutter Clean Architecture in Rorty is a sample project that presents

Jan 1, 2023

COVID-19 application made with Flutter, following Test Driven Development (TDD) and Clean Architecture along with Internationalization with JSON.

COVID-19 application made with Flutter, following Test Driven Development (TDD) and Clean Architecture along with Internationalization with JSON.

Covid App COVID-19 application made with Flutter, following Test Driven Development (TDD) and Clean Architecture along with Internationalization with

Aug 4, 2022

Starting template for a new Flutter project. Using clean architecture + Riverpod.

flutter_project_template_riverpod Installation Add Flutter to your machine Open this project folder with Terminal/CMD Ensure there's no cache/build le

Dec 27, 2022

Flutter boilerplate with TDD architecture

flutter_tdd_architecture A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you

May 25, 2022

A beautiful design and useful project for Building a flutter knowledge architecture

Flutter Dojo Change log Flutter Dojo Change Log 我的网站 https://xuyisheng.top/ Wiki Flutter Dojo Wiki 体验APK Github Actions APK download 认识Flutter是在18年,移动

Dec 21, 2022

A Flutter repo with a ready-to-go architecture containing flavors, bloc, device settings, json serialization and connectivity

A Flutter repo with a ready-to-go architecture containing flavors, bloc, device settings, json serialization and connectivity

Flutter Ready to Go A Flutter repo with a ready-to-go architecture containing flavors, bloc, device settings, json serialization and connectivity. Why

Nov 11, 2022
Releases(v0.0.5)
  • v0.0.5(Jun 1, 2022)

    [0.0.5] - 2022-06-01

    Flutter updated to 3.0 and Dart to 2.17.
    Configuring internationalization.

    • Using DART 2.17 new super arguments.
    • Using lint 2.0.1.
    • Using Flutter l10n for internationalization with ARB files.
    Source code(tar.gz)
    Source code(zip)
  • v0.0.3(Mar 22, 2022)

    Placing example files in example subfolders. Adding Stream API abstract classes and interfaces in Domain Layer.

    Refactored the whole structure to move example specific files into new example subfolders.
    This way when reusing this template you will find example app files separated from generic files.
    These generic will either be reused as is (abstract classes, interfaces) or will be edited (providers, exports).
    While example files will probably be deleted after serving their role as examples.
    Added abstract stream API usecase and stream API repository interface to domain layer.

    Source code(tar.gz)
    Source code(zip)
  • v0.0.2(Mar 19, 2022)

    Hidding usecase injected dependencies in private instance variables.

    Important to protect injected implementations of repositories and prevent direct access to storage.
    Maintaining a reference to the repository in the DomainLayer object itself, but cast to its StateNotifier subtype, allowing riverpod to watch state changes in the repository without full access to its API (it is the repository object by accessed by its Notifier subtype.

    Source code(tar.gz)
    Source code(zip)
  • v0.0.1(Mar 18, 2022)

    Template for Flutter Layered Architecture - Version 0.0.1

    Defined Layered Architecture Structure with each layer in an internal package:

    • Core (Basic interfaces and utilities)
    • Domain Layer (Business Entities and Business Rules)
    • Data Layer (Persistence)
    • Service Layer (External services)
    • Presentation Layer (UI)
    • DI Layer (Dependency Injection)

    Layered Implementation using Riverpod Providers and Freezed libraries:

    • Per layer exports to define public/private members for each layer
    • Each layer has a AppLayer Object to coordinate inter-layer interactions
    • Using Riverpod for layer instantiation and initialization
    • Using Riverpod for layer configuration with Dependency Inversion
    • Using Riverpod to expose layer implementations
    • Using Freezed classes for Entities

    main() implementation to provide global injection scope and initialize all layers:

    • Wrap the whole application in Riverpod ProviderScope
    • Use a FutureProvider to:
      • Async initialize the DI Layer (which initialize and configure all other layers)
      • Create main App widget after initialization

    Example Usecase Implementation

    • Domain entities, Domain exceptions, Domain repository interfaces, Domain usecases
    • Data repository implementation
    • Dependency Inversion (also Dependency Injection) via AppLayer instances and providers

    Common Code extracted to correct locations

    • Common code in Core folder
    • Common pages in /lib/presentation/common/page
    • Named routes configuration and implementation

    Testing Domain Usecase

    • Testing Domain Usecase business rules with Mockito
    Source code(tar.gz)
    Source code(zip)
Owner
Ricardo Nogueira
Flutter development done right!
Ricardo Nogueira
Flutter Architecture Blueprints is a project that introduces MVVM architecture and project structure approaches to developing Flutter apps.

Flutter Architecture Blueprints Flutter Architecture Blueprints is a project that introduces MVVM architecture and project structure approaches to dev

Daichi Furiya 1.5k Dec 31, 2022
Ouday 25 Dec 15, 2022
Flutter-clean-architecture - A simple flutter project developed with TDD and using Clean Architecture principles.

Clean Architecture This is a study project to practice TDD and a good approach of Clean Architecture for flutter projects. It is based on Reso Coder s

Luiz Paulo Franz 8 Jul 21, 2022
Flutter Architecture inspired by Domain Driven Design, Onion and Clean Architecture

Inspiring Domain Driven Design Flutter Architecture Please take a look at my slides to learn more Strategic Domain Driven Design For Improving Flutter

Majid Hajian 324 Dec 25, 2022
Proyect with Clean Architecture / Hexagonal Architecture - Patron BLoC - The MovieDB API

flutter_movies_db A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you starte

null 2 Sep 22, 2022
[Flutter SDK V.2] - Youtube Video is a Flutter application built to demonstrate the use of Modern development tools with best practices implementation like Clean Architecture, Modularization, Dependency Injection, BLoC, etc.

[Flutter SDK V.2] - Youtube Video is a Flutter application built to demonstrate the use of Modern development tools with best practices implementation like Clean Architecture, Modularization, Dependency Injection, BLoC, etc.

R. Rifa Fauzi Komara 17 Jan 2, 2023
Weather app using Bloc architecture pattern & generic HTTP client with interface implementation and much more for more detail read Readme

weather Weather application for current weather, hourly forecast for 48 hours, Daily forecast for 7 days and national weather alerts. How to Run Insta

Jibran Ahmed SiddiQui 9 Oct 29, 2022
Purpose of this project is to create extendable architecture of making platform aware Widgets which automatically select platform specific implementation

Old good factory Main obstacle in creating native experience on Flutter is the fact that you are asked to rebuild two layouts using platform specific

Swav Kulinski (Robotoaster) 101 Oct 14, 2022
A set of widgets to help with the implementation of the Provider architecture as shown by FilledStacks

Provider Architecture - Deprecated on 21 April 2020 Notice V2 of this package is renamed to Stacked Stacked is the name of the architecture that was o

Dane Mackier 84 Dec 16, 2021
Get It - Simple direct Service Locator that allows to decouple the interface from a concrete implementation and to access the concrete implementation from everywhere in your App. Maintainer: @escamoteur

❤️ Sponsor get_it This is a simple Service Locator for Dart and Flutter projects with some additional goodies highly inspired by Splat. It can be used

Flutter Community 1k Jan 1, 2023