Guide Architecture

Flutter Clean Architecture with BLoC: how I structure production apps

Layers, folders, error handling, dependency injection and testing, with small examples you can copy.

Short answer

Clean Architecture splits every feature of a Flutter app into three layers: data (API calls, local storage and models), domain (entities, repository contracts and use cases) and presentation (BLoCs, pages and widgets). BLoC manages state: widgets add events, the BLoC calls a use case and emits new states, and widgets only render those states. Use cases return Either<Failure, T>, so errors travel as values instead of exceptions, and GetIt wires the layers together. The result is an app where features change independently and business logic can be tested without a device.

I work on a production Flutter app built this way: a dozen features, around 90 use cases and 20 BLoCs, with 180+ builds shipped through pull-request reviews. I’ve used the same structure in client apps too, such as a fitness coaching platform.

This guide shows the structure I use, the code patterns behind each layer, and the trade-offs, with small examples for a simple tasks feature that you can adapt.

Why Clean Architecture and BLoC

  • Features change independently. Each feature owns its data, domain and presentation code, so a change to one rarely touches another.
  • Business rules are testable. Use cases and BLoCs are plain Dart, so they can be unit-tested without a device or emulator.
  • The backend can change. Screens talk to repository contracts, not to a REST API or Firebase directly, so swapping a data source stays inside the data layer.
  • Every feature reads the same way. New teammates learn one pattern and can work anywhere in the app, and code reviews can focus on logic instead of structure.
  • State is predictable. With BLoC, every change starts with an event and ends with a new state, which makes bugs easy to trace.

The three layers

LayerContainsDepends on
PresentationPages, widgets, bottom sheets and BLoCsDomain
DomainEntities, repository contracts and use casesNothing: plain Dart
DataRemote and local data sources, models and repository implementationsDomain

The one rule: dependencies point inward. The domain layer knows nothing about Flutter, HTTP or Firebase, and the presentation layer never calls a data source directly.

Project structure

I organise by feature first, then by layer. Shared building blocks live in core, and code used by several features lives in a common module with its own layers.

lib/
├── core/
│   ├── api/          API client, endpoints, response wrapper
│   ├── di/           GetIt registrations
│   ├── error/        exceptions.dart, failures.dart
│   ├── routes/       route names and the router
│   └── usecases/     UseCase base class and Result typedef
└── src/
    ├── common/       shared data, domain, blocs and widgets
    └── features/
        └── tasks/
            ├── data/
            │   ├── datasource/   tasks_remote_datasource.dart
            │   ├── models/       task_model.dart
            │   └── repository/   tasks_repository_impl.dart
            ├── domain/
            │   ├── entities/     task.dart
            │   ├── repository/   tasks_repository.dart
            │   └── usecases/     get_tasks.dart, complete_task.dart
            └── presentation/
                ├── bloc/         tasks_bloc.dart, tasks_event.dart, tasks_state.dart
                ├── pages/
                ├── sheets/
                └── widgets/

Conventions that keep it tidy

  • One BLoC per screen or panel. A feature can have several: a list, a detail view and an insights panel each get their own, so no BLoC grows into a god object.
  • UI-only models stay in presentation. Things like a filter selection never leak into the domain layer.
  • Bottom sheets get their own folder. They are often complex enough to deserve it, and they are easy to find.
  • Routes and dependency injection are central. One router and one injection container in core, so every feature is wired the same way.

The shared core: Result, use cases and failures

A few small types in core make every feature consistent. Either comes from the dartz package (fpdart works the same way).

// core/usecases/either.dart
typedef Result<T> = Either<Failure, T>;
typedef ResultFuture<T> = Future<Result<T>>;

// core/usecases/usecases.dart
abstract class UseCase<T, Params> {
  ResultFuture<T> call(Params params);
}

// core/error/failures.dart
abstract class Failure extends Equatable {
  const Failure(this.message);
  final String message;

  @override
  List<Object?> get props => [message];
}

class ServerFailure extends Failure {
  const ServerFailure(super.message);
}

class AuthFailure extends Failure {
  const AuthFailure(super.message);
}
  • Typed failures. Separate failures for server, network, not found, unauthorised, forbidden and validation errors let each screen react properly, for example sending the user to sign in on an auth failure.
  • One API client. Every request goes through a single client that handles auth status codes, including expired tokens, in one place, so features never deal with raw HTTP responses.

Domain layer: entities, contracts and use cases

// domain/entities/task.dart
class Task extends Equatable {
  const Task({required this.id, required this.title, required this.done});
  final String id;
  final String title;
  final bool done;

  @override
  List<Object?> get props => [id, title, done];
}

// domain/repository/tasks_repository.dart
abstract class TasksRepository {
  ResultFuture<List<Task>> getTasks(String projectId);
}

// domain/usecases/get_tasks.dart
class GetTasks implements UseCase<List<Task>, String> {
  const GetTasks(this._repository);
  final TasksRepository _repository;

  @override
  ResultFuture<List<Task>> call(String projectId) => _repository.getTasks(projectId);
}
  • Entities are plain Dart. No JSON, no Flutter imports, compared by value with Equatable.
  • Repositories are contracts. The domain says what it needs; the data layer decides how to get it.
  • One use case per action. Get tasks, complete a task, delete a task. Small classes are easy to test and to find.

Data layer: data sources, models and repositories

class TasksRepositoryImpl implements TasksRepository {
  const TasksRepositoryImpl(this._remote);
  final TasksRemoteDataSource _remote;

  @override
  ResultFuture<List<Task>> getTasks(String projectId) async {
    try {
      final models = await _remote.getTasks(projectId);
      return Right(models.map((m) => m.toEntity()).toList());
    } on UnauthorizedException {
      return const Left(AuthFailure('Please sign in again.'));
    } on ServerException catch (e) {
      return Left(ServerFailure(e.message));
    }
  }
}
  • Data sources throw, repositories translate. A data source throws typed exceptions; the repository catches them and returns failures, so nothing above it ever sees an exception.
  • Models handle JSON. A model parses the API response and maps itself to an entity, so API changes stay in one file.
  • Several data sources per feature are fine. One for the list, one for reports, one for insights. The repository decides how to combine them.

Presentation layer: BLoC

The BLoC receives events from the UI, calls use cases and emits states. Sealed state classes let the UI handle every case with a switch.

class TasksBloc extends Bloc<TasksEvent, TasksState> {
  TasksBloc({required GetTasks getTasks})
      : _getTasks = getTasks,
        super(const TasksInitial()) {
    on<TasksRequested>(_onRequested);
  }

  final GetTasks _getTasks;

  Future<void> _onRequested(TasksRequested event, Emitter<TasksState> emit) async {
    emit(const TasksLoading());
    final result = await _getTasks(event.projectId);
    result.fold(
      (failure) => emit(TasksError(failure.message)),
      (tasks) => emit(TasksLoaded(tasks)),
    );
  }
}
BlocBuilder<TasksBloc, TasksState>(
  builder: (context, state) => switch (state) {
    TasksInitial() => const SizedBox.shrink(),
    TasksLoading() => const Center(child: CircularProgressIndicator()),
    TasksLoaded(:final tasks) => TaskList(tasks: tasks),
    TasksError(:final message) => ErrorView(message: message),
  },
)
  • Bloc with events, even for simple screens. I use full Bloc everywhere, so every screen reads the same way. Cubit is fine for very simple state, but mixing both makes a codebase less consistent.
  • Scope BLoCs to their screen. Create the BLoC with the page and let it close with the page. Keep only truly app-wide state, such as the signed-in user, above the router.
  • Use BlocListener for one-off effects. Navigation, snackbars and dialogs belong in a listener, not in build.
  • Widgets only render. No API calls, no business rules, no parsing. If a widget needs data, it reads it from a state.

Dependency injection with GetIt

final sl = GetIt.instance;

Future<void> initTasks() async {
  sl
    ..registerFactory(() => TasksBloc(getTasks: sl()))
    ..registerLazySingleton(() => GetTasks(sl()))
    ..registerLazySingleton<TasksRepository>(() => TasksRepositoryImpl(sl()))
    ..registerLazySingleton<TasksRemoteDataSource>(() => TasksRemoteDataSourceImpl(sl()));
}
  • BLoCs are factories. Each screen gets a fresh instance, so no state leaks between visits.
  • Everything else is a lazy singleton. Use cases, repositories and data sources are created once, on first use.
  • Register by contract. Registering TasksRepository rather than the implementation lets tests swap in a fake with one line.

Testing each layer

The layers make tests small. In a client project with this structure, unit and widget tests cover data sources, BLoCs and domain logic, using a fake backend and mocked sign-in.

class MockGetTasks extends Mock implements GetTasks {}

void main() {
  late MockGetTasks getTasks;
  setUp(() => getTasks = MockGetTasks());

  blocTest<TasksBloc, TasksState>(
    'emits loading, then loaded',
    build: () {
      when(() => getTasks(any())).thenAnswer((_) async => const Right([]));
      return TasksBloc(getTasks: getTasks);
    },
    act: (bloc) => bloc.add(const TasksRequested('p1')),
    expect: () => [const TasksLoading(), const TasksLoaded([])],
  );
}
  • Domain. Test each use case against a mocked repository.
  • Data. Test that repositories turn exceptions into the right failures, and that models parse real API responses.
  • Presentation. Test state sequences with bloc_test, and key screens with widget tests.

When it’s too much

  • It adds files. A simple read becomes an entity, a model, a data source, a repository contract, an implementation, a use case and a BLoC. Templates such as Mason bricks generate them in seconds.
  • Prototypes don’t need it. For a demo or a two-screen app, feature folders with a Cubit are enough. Move to full layers when the app and the team grow.
  • Don’t add layers for their own sake. If a use case only passes data through, keep it anyway for consistency, but don’t invent extra layers on top.

FAQ

What is Clean Architecture in Flutter?

A way to split each feature into three layers: data (API calls, storage, models), domain (entities, repository contracts, use cases) and presentation (state management and widgets). Dependencies point inward, so business rules don’t depend on Flutter or the backend.

Is BLoC a good fit for Clean Architecture?

Yes. BLoC sits in the presentation layer: it receives events from the UI, calls use cases from the domain layer and emits states for the widgets. That keeps business logic out of widgets and makes it testable.

Should I use Bloc or Cubit?

Cubit is simpler and fine for small, local state. Bloc adds events, which make complex flows easier to trace and test. Picking one style for the whole app keeps the codebase consistent; I use Bloc everywhere.

Where do API calls go in a Flutter Clean Architecture app?

In data sources in the data layer. Repositories call the data sources, convert exceptions into failures and map models to entities. Use cases call repositories, and BLoCs call use cases. Widgets never call APIs.

Is Clean Architecture overkill for a small Flutter app?

For a prototype or a very small app, often yes. For an app that will grow, have several developers or live for years, the extra files pay for themselves in easier changes, reviews and tests.

Can I use Riverpod instead of BLoC with Clean Architecture?

Yes. The layers stay the same and only the presentation layer changes. I’ve shipped Clean Architecture with BLoC in most apps and with Riverpod in a marketplace app.