Implementing an offline-first app using Clean Architecture in Flutter involves several steps. Clean Architecture promotes separation of concerns, making your codebase more maintainable and testable. Here’s a high-level overview of how to structure your Flutter app with an offline-first approach:
1. Project Structure
Start by organizing your project into layers according to Clean Architecture:
lib/
├── core/
│ ├── error/
│ ├── usecases/
│ └── utils/
├── features/
│ ├── feature_name/
│ │ ├── data/
│ │ │ ├── models/
│ │ │ ├── repositories/
│ │ │ └── datasources/
│ │ ├── domain/
│ │ │ ├── entities/
│ │ │ ├── repositories/
│ │ │ └── usecases/
│ │ └── presentation/
│ │ ├── pages/
│ │ └── widgets/
└── main.dart
2. Data Layer
2.1. Models
Define your data models in the data/models directory. These models will represent the data structure you will be working with.
class UserModel {
final String id;
final String name;
UserModel({required this.id, required this.name});
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
id: json['id'],
name: json['name'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
};
}
}
2.2. Data Sources
Create a local data source for offline storage (e.g., using SQLite, Hive, or Shared Preferences) and a remote data source for API calls.
abstract class UserLocalDataSource {
Future<List<UserModel>> getUsers();
Future<void> cacheUsers(List<UserModel> users);
}
class UserLocalDataSourceImpl implements UserLocalDataSource {
// Use Hive, SQLite, or Shared Preferences for local storage
@override
Future<List<UserModel>> getUsers() {
// Implement local data retrieval
}
@override
Future<void> cacheUsers(List<UserModel> users) {
// Implement local data caching
}
}
abstract class UserRemoteDataSource {
Future<List<UserModel>> fetchUsers();
}
class UserRemoteDataSourceImpl implements UserRemoteDataSource {
@override
Future<List<UserModel>> fetchUsers() {
// Implement API call
}
}
2.3. Repositories
Create a repository that will use both data sources.
abstract class UserRepository {
Future<List<UserModel>> getUsers();
}
class UserRepositoryImpl implements UserRepository {
final UserLocalDataSource localDataSource;
final UserRemoteDataSource remoteDataSource;
UserRepositoryImpl({
required this.localDataSource,
required this.remoteDataSource,
});
@override
Future<List<UserModel>> getUsers() async {
try {
final remoteUsers = await remoteDataSource.fetchUsers();
await localDataSource.cacheUsers(remoteUsers);
return remoteUsers;
} catch (e) {
return await localDataSource.getUsers();
}
}
}
3. Domain Layer
3.1. Entities
Define your entities in the domain/entities directory. These are the core business objects.
class User {
final String id;
final String name;
User({required this.id, required this.name});
}
3.2. Use Cases
Create use cases that will interact with the repository.
class GetUsers {
final UserRepository repository;
GetUsers(this.repository);
Future<List<User>> call() async {
return await repository.getUsers();
}
}
4. Presentation Layer
4.1. Pages and Widgets
Create your UI components in the presentation/pages and presentation/widgets directories. Use a state management solution (like Provider, Riverpod, or Bloc) to manage the state of your app.
class UserPage extends StatelessWidget {
final GetUsers getUsers;
UserPage({required this.getUsers});
@override
Widget build(BuildContext context) {
return FutureBuilder<List<User>>(
future: getUsers(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
final users = snapshot.data!;
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(users[index].name),
);
},
);
}
},
);
}
}
5. Main Entry Point
In your main.dart, set up your dependency injection and run the app.
void main() {
final userLocalDataSource = UserLocalDataSourceImpl();
final userRemoteDataSource = UserRemoteDataSourceImpl();
final userRepository = UserRepositoryImpl(
localDataSource: userLocalDataSource,
remoteDataSource: userRemoteDataSource,
);
final getUsers = GetUsers(userRepository);
runApp(MyApp(getUsers: getUsers));
}
class MyApp extends StatelessWidget {
final GetUsers getUsers;
MyApp({required this.getUsers});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: UserPage(getUsers: getUsers),
);
}
}
6. Testing
Make sure to write unit tests for your use cases, repositories, and data sources to ensure that your app behaves as expected.
Conclusion
This is a basic outline of how to implement an offline-first app using Clean Architecture in Flutter. You can expand upon this by adding error handling, caching strategies, and more complex state management as needed. The key is to keep your layers separate and maintain a clear flow of data from the presentation layer down to the data layer.