Implementing an offline-first app in Flutter using Clean Architecture involves structuring your app in a way that ensures separation of concerns, scalability, and maintainability while prioritizing offline functionality. Below is a step-by-step guide to help you achieve this:
1. Understand Clean Architecture
Clean Architecture divides your app into layers to ensure separation of concerns. The typical layers are:
- Presentation Layer: UI and state management (e.g., widgets, BLoC, Provider, etc.).
- Domain Layer: Business logic, use cases, and entities (independent of frameworks and external systems).
- Data Layer: Data sources (local and remote), repositories, and models.
For an offline-first app, the data layer will prioritize local storage and sync with remote data when online.
2. Define the Offline-First Strategy
An offline-first app ensures that the app works seamlessly without an internet connection and syncs data when connectivity is restored. Key components of this strategy include:
- Local Storage: Use a local database (e.g., SQLite via
sqflite, Hive, or Drift) to store data.
- Remote Data Source: Use an API (e.g., REST or GraphQL) to fetch and sync data.
- Synchronization: Implement a mechanism to sync local data with the remote server when online.
- Conflict Resolution: Handle conflicts between local and remote data (e.g., last-write-wins, versioning, etc.).
- Connectivity Awareness: Detect network status to trigger sync or inform the user.
3. Set Up Your Project Structure
Organize your Flutter project following Clean Architecture principles. Here's an example structure:
lib/
├── core/
│ ├── error/
│ │ └── failures.dart
│ ├── network/
│ │ └── network_info.dart
│ └── usecases/
│ └── usecase.dart
├── features/
│ └── todo/
│ ├── data/
│ │ ├── datasources/
│ │ │ ├── local_datasource.dart
│ │ │ └── remote_datasource.dart
│ │ ├── models/
│ │ │ └── todo_model.dart
│ │ └── repositories/
│ │ └── todo_repository_impl.dart
│ ├── domain/
│ │ ├── entities/
│ │ │ └── todo_entity.dart
│ │ ├── repositories/
│ │ │ └── todo_repository.dart
│ │ └── usecases/
│ │ ├── get_todos.dart
│ │ ├── add_todo.dart
│ │ └── sync_todos.dart
│ └── presentation/
│ ├── bloc/
│ │ └── todo_bloc.dart
│ └── pages/
│ └── todo_page.dart
├── injection_container.dart
└── main.dart
4. Choose Dependencies
Add the necessary dependencies to your pubspec.yaml file. Below are some commonly used packages for an offline-first app:
dependencies:
flutter:
sdk: flutter
flutter_bloc: ^8.1.1 # State management
equatable: ^2.0.5 # For value equality
dartz: ^0.10.1 # For functional programming (Either, Option, etc.)
connectivity_plus: ^3.0.2 # For network status
sqflite: ^2.2.0 # For SQLite database
path_provider: ^2.0.11 # For file system access
http: ^0.13.5 # For API calls
get_it: ^7.2.0 # For dependency injection
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.3.2 # For unit testing
5. Implement the Domain Layer
The domain layer is the core of your app and contains business logic. It is independent of any external frameworks.
Entities
Entities represent the core data models of your app. For example, a Todo entity:
// lib/features/todo/domain/entities/todo_entity.dart
import 'package:equatable/equatable.dart';
class TodoEntity extends Equatable {
final String id;
final String title;
final bool isCompleted;
final DateTime? lastUpdated;
const TodoEntity({
required this.id,
required this.title,
required this.isCompleted,
this.lastUpdated,
});
@override
List<Object?> get props => [id, title, isCompleted, lastUpdated];
}
Repositories (Abstract)
Define an abstract repository interface that the data layer will implement:
// lib/features/todo/domain/repositories/todo_repository.dart
import 'package:dartz/dartz.dart';
import '../../../../core/error/failures.dart';
import '../entities/todo_entity.dart';
abstract class TodoRepository {
Future<Either<Failure, List<TodoEntity>>> getTodos();
Future<Either<Failure, void>> addTodo(TodoEntity todo);
Future<Either<Failure, void>> syncTodos();
}
Use Cases
Use cases encapsulate business logic. For example, a use case to get todos:
// lib/features/todo/domain/usecases/get_todos.dart
import 'package:dartz/dartz.dart';
import '../../../../core/error/failures.dart';
import '../../../../core/usecases/usecase.dart';
import '../entities/todo_entity.dart';
import '../repositories/todo_repository.dart';
class GetTodos implements UseCase<List<TodoEntity>, NoParams> {
final TodoRepository repository;
GetTodos(this.repository);
@override
Future<Either<Failure, List<TodoEntity>>> call(NoParams params) async {
return await repository.getTodos();
}
}
6. Implement the Data Layer
The data layer handles data retrieval and storage, both locally and remotely.
Models
Models are data-layer representations of entities, often used for serialization/deserialization:
// lib/features/todo/data/models/todo_model.dart
import '../../domain/entities/todo_entity.dart';
class TodoModel extends TodoEntity {
TodoModel({
required String id,
required String title,
required bool isCompleted,
DateTime? lastUpdated,
}) : super(
id: id,
title: title,
isCompleted: isCompleted,
lastUpdated: lastUpdated,
);
factory TodoModel.fromJson(Map<String, dynamic> json) {
return TodoModel(
id: json['id'],
title: json['title'],
isCompleted: json['isCompleted'],
lastUpdated: DateTime.parse(json['lastUpdated']),
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'isCompleted': isCompleted,
'lastUpdated': lastUpdated?.toIso8601String(),
};
}
factory TodoModel.fromEntity(TodoEntity entity) {
return TodoModel(
id: entity.id,
title: entity.title,
isCompleted: entity.isCompleted,
lastUpdated: entity.lastUpdated,
);
}
}
Local Data Source
Implement a local data source using sqflite for persistent storage:
// lib/features/todo/data/datasources/local_datasource.dart
import 'package:sqflite/sqflite.dart';
import '../models/todo_model.dart';
class LocalDataSource {
final Database database;
LocalDataSource(this.database);
Future<List<TodoModel>> getTodos() async {
final List<Map<String, dynamic>> maps = await database.query('todos');
return maps.map((map) => TodoModel.fromJson(map)).toList();
}
Future<void> addTodo(TodoModel todo) async {
await database.insert(
'todos',
todo.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<void> cacheTodos(List<TodoModel> todos) async {
await database.delete('todos');
for (var todo in todos) {
await addTodo(todo);
}
}
}
Remote Data Source
Implement a remote data source to fetch and sync data with an API:
// lib/features/todo/data/datasources/remote_datasource.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../models/todo_model.dart';
class RemoteDataSource {
final http.Client client;
RemoteDataSource(this.client);
Future<List<TodoModel>> getTodos() async {
final response = await client.get(Uri.parse('https://api.example.com/todos'));
if (response.statusCode == 200) {
final List<dynamic> jsonList = jsonDecode(response.body);
return jsonList.map((json) => TodoModel.fromJson(json)).toList();
} else {
throw Exception('Failed to fetch todos');
}
}
Future<void> syncTodos(List<TodoModel> todos) async {
final response = await client.post(
Uri.parse('https://api.example.com/todos/sync'),
body: jsonEncode(todos.map((todo) => todo.toJson()).toList()),
headers: {'Content-Type': 'application/json'},
);
if (response.statusCode != 200) {
throw Exception('Failed to sync todos');
}
}
}
Repository Implementation
The repository acts as a bridge between the domain and data layers, deciding whether to use local or remote data:
// lib/features/todo/data/repositories/todo_repository_impl.dart
import 'package:dartz/dartz.dart';
import '../../../../core/error/failures.dart';
import '../../../../core/network/network_info.dart';
import '../../domain/entities/todo_entity.dart';
import '../../domain/repositories/todo_repository.dart';
import '../datasources/local_datasource.dart';
import '../datasources/remote_datasource.dart';
import '../models/todo_model.dart';
class TodoRepositoryImpl implements TodoRepository {
final LocalDataSource localDataSource;
final RemoteDataSource remoteDataSource;
final NetworkInfo networkInfo;
TodoRepositoryImpl({
required this.localDataSource,
required this.remoteDataSource,
required this.networkInfo,
});
@override
Future<Either<Failure, List<TodoEntity>>> getTodos() async {
try {
// Always return local data first (offline-first)
final localTodos = await localDataSource.getTodos();
if (await networkInfo.isConnected) {
// If online, fetch remote data and cache it locally
final remoteTodos = await remoteDataSource.getTodos();
await localDataSource.cacheTodos(remoteTodos);
return Right(remoteTodos);
}
return Right(localTodos);
} catch (e) {
return Left(ServerFailure());
}
}
@override
Future<Either<Failure, void>> addTodo(TodoEntity todo) async {
try {
final todoModel = TodoModel.fromEntity(todo);
// Always save locally
await localDataSource.addTodo(todoModel);
if (await networkInfo.isConnected) {
// If online, sync with remote
await remoteDataSource.syncTodos([todoModel]);
}
return const Right(null);
} catch (e) {
return Left(ServerFailure());
}
}
@override
Future<Either<Failure, void>> syncTodos() async {
try {
if (await networkInfo.isConnected) {
final localTodos = await localDataSource.getTodos();
await remoteDataSource.syncTodos(localTodos);
return const Right(null);
}
return Left(NetworkFailure());
} catch (e) {
return Left(ServerFailure());
}
}
}
7. Implement the Presentation Layer
The presentation layer handles UI and state management. Here, we'll use the BLoC pattern for state management.
BLoC
Create a BLoC to manage the state of the todo feature:
// lib/features/todo/presentation/bloc/todo_bloc.dart
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import '../../domain/entities/todo_entity.dart';
import '../../domain/usecases/get_todos.dart';
import '../../domain/usecases/add_todo.dart';
import '../../domain/usecases/sync_todos.dart';
part 'todo_event.dart';
part 'todo_state.dart';
class TodoBloc extends Bloc<TodoEvent, TodoState> {
final GetTodos getTodos;
final AddTodo addTodo;
final SyncTodos syncTodos;
TodoBloc({
required this.getTodos,
required this.addTodo,
required this.syncTodos,
}) : super(TodoInitial()) {
on<LoadTodos>((event, emit) async {
emit(TodoLoading());
final result = await getTodos(NoParams());
result.fold(
(failure) => emit(TodoError('Failed to load todos')),
(todos) => emit(TodoLoaded(todos)),
);
});
on<AddTodoEvent>((event, emit) async {
final result = await addTodo(event.todo);
result.fold(
(failure) => emit(TodoError('Failed to add todo')),
(_) => add(LoadTodos()),
);
});
on<SyncTodosEvent>((event, emit) async {
final result = await syncTodos();
result.fold(
(failure) => emit(TodoError('Failed to sync todos')),
(_) => add(LoadTodos()),
);
});
}
}
BLoC Events and States
// lib/features/todo/presentation/bloc/todo_event.dart
part of 'todo_bloc.dart';
abstract class TodoEvent extends Equatable {
const TodoEvent();
@override
List<Object> get props => [];
}
class LoadTodos extends TodoEvent {}
class AddTodoEvent extends TodoEvent {
final TodoEntity todo;
const AddTodoEvent(this.todo);
@override
List<Object> get props => [todo];
}
class SyncTodosEvent extends TodoEvent {}
// lib/features/todo/presentation/bloc/todo_state.dart
part of 'todo_bloc.dart';
abstract class TodoState extends Equatable {
const TodoState();
@override
List<Object> get props => [];
}
class TodoInitial extends TodoState {}
class TodoLoading extends TodoState {}
class TodoLoaded extends TodoState {
final List<TodoEntity> todos;
const TodoLoaded(this.todos);
@override
List<Object> get props => [todos];
}
class TodoError extends TodoState {
final String message;
const TodoError(this.message);
@override
List<Object> get props => [message];
}
UI
Create a simple UI to display todos and allow adding new ones:
// lib/features/todo/presentation/pages/todo_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/entities/todo_entity.dart';
import '../bloc/todo_bloc.dart';
class TodoPage extends StatelessWidget {
const TodoPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Offline-First Todos')),
body: BlocBuilder<TodoBloc, TodoState>(
builder: (context, state) {
if (state is TodoLoading) {
return const Center(child: CircularProgressIndicator());
} else if (state is TodoLoaded) {
return ListView.builder(
itemCount: state.todos.length,
itemBuilder: (context, index) {
final todo = state.todos[index];
return ListTile(
title: Text(todo.title),
trailing: Icon(
todo.isCompleted ? Icons.check : Icons.close,
color: todo.isCompleted ? Colors.green : Colors.red,
),
);
},
);
} else if (state is TodoError) {
return Center(child: Text(state.message));
}
return const Center(child: Text('Press the button to load todos'));
},
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: () {
final todo = TodoEntity(
id: DateTime.now().toString(),
title: 'New Todo',
isCompleted: false,
lastUpdated: DateTime.now(),
);
context.read<TodoBloc>().add(AddTodoEvent(todo));
},
child: const Icon(Icons.add),
),
const SizedBox(height: 10),
FloatingActionButton(
onPressed: () {
context.read<TodoBloc>().add(SyncTodosEvent());
},
child: const Icon(Icons.sync),
),
],
),
);
}
}
8. Handle Network Connectivity
Use the connectivity_plus package to detect network status and trigger sync when online:
// lib/core/network/network_info.dart
import 'package:connectivity_plus/connectivity_plus.dart';
abstract class NetworkInfo {
Future<bool> get isConnected;
}
class NetworkInfoImpl implements NetworkInfo {
final Connectivity connectivity;
NetworkInfoImpl(this.connectivity);
@override
Future<bool> get isConnected async {
final result = await connectivity.checkConnectivity();
return result != ConnectivityResult.none;
}
}
You can also listen to connectivity changes and trigger sync automatically:
void listenToConnectivity(TodoBloc bloc) {
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
if (result != ConnectivityResult.none) {
bloc.add(SyncTodosEvent());
}
});
}
9. Set Up Dependency Injection
Use get_it to manage dependencies:
// lib/injection_container.dart
import 'package:get_it/get_it.dart';
import 'package:http/http.dart' as http;
import 'package:sqflite/sqflite.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'core/network/network_info.dart';
import 'features/todo/data/datasources/local_datasource.dart';
import 'features/todo/data/datasources/remote_datasource.dart';
import 'features/todo/data/repositories/todo_repository_impl.dart';
import 'features/todo/domain/repositories/todo_repository.dart';
import 'features/todo/domain/usecases/get_todos.dart';
import 'features/todo/domain/usecases/add_todo.dart';
import 'features/todo/domain/usecases/sync_todos.dart';
import 'features/todo/presentation/bloc/todo_bloc.dart';
final sl = GetIt.instance;
Future<void> init() async {
// External
final database = await openDatabase('todos.db', version: 1, onCreate: (db, version) async {
await db.execute('''
CREATE TABLE todos (
id TEXT PRIMARY KEY,
title TEXT,
isCompleted INTEGER,
lastUpdated TEXT
)
''');
});
sl.registerLazySingleton<Database>(() => database);
sl.registerLazySingleton(() => http.Client());
sl.registerLazySingleton(() => Connectivity());
// Core
sl.registerLazySingleton<NetworkInfo>(() => NetworkInfoImpl(sl()));
// Data sources
sl.registerLazySingleton(() => LocalDataSource(sl()));
sl.registerLazySingleton(() => RemoteDataSource(sl()));
// Repository
sl.registerLazySingleton<TodoRepository>(() => TodoRepositoryImpl(
localDataSource: sl(),
remoteDataSource: sl(),
networkInfo: sl(),
));
// Use cases
sl.registerLazySingleton(() => GetTodos(sl()));
sl.registerLazySingleton(() => AddTodo(sl()));
sl.registerLazySingleton(() => SyncTodos(sl()));
// BLoC
sl.registerFactory(() => TodoBloc(
getTodos: sl(),
addTodo: sl(),
syncTodos: sl(),
));
}
10. Initialize the App
Set up the app in main.dart:
// lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'features/todo/presentation/bloc/todo_bloc.dart';
import 'features/todo/presentation/pages/todo_page.dart';
import 'injection_container.dart' as di;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await di.init();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => di.sl<TodoBloc>()..add(LoadTodos()),
child: MaterialApp(
title: 'Offline-First App',
theme: ThemeData(primarySwatch: Colors.blue),
home: const TodoPage(),
),
);
}
}
11. Handle Data Synchronization
For robust synchronization, consider:
- Timestamps: Use
lastUpdated fields to determine which data is newer.
- Conflict Resolution: Implement strategies like last-write-wins or user prompts for conflicts.
- Background Sync: Use packages like
workmanager to schedule background sync tasks.
12. Test Your App
Write unit and integration tests to ensure your app works offline and syncs correctly. Use mockito to mock dependencies.
13. Additional Considerations
- Error Handling: Provide meaningful feedback to users when operations fail.
- User Experience: Show offline status, sync progress, and pending actions.
- Security: Encrypt sensitive data in the local database.
- Scalability: Use a more advanced database like Drift or a backend sync solution like Firebase for larger apps.
By following this guide, you'll have a robust offline-first Flutter app built with Clean Architecture, ensuring maintainability, testability, and a great user experience.