A production-ready Flutter boilerplate following Clean Architecture principles with BLoC state management, modular design, and comprehensive component system.
- Features
- Architecture
- Project Structure
- Getting Started
- Module System
- State Management
- Components
- Development Guide
- Best Practices
- Contributing
- Clean Architecture - Separation of concerns with data, domain, and presentation layers
- BLoC Pattern - Predictable state management with flutter_bloc
- Module System - Feature-based modular architecture with dependency injection
- Form Validation - Type-safe form validation with FormZ
- Internationalization - Multi-language support with flutter_localizations
- Theme Support - Dark/Light theme with custom theming
- Network Layer - Dio-based HTTP client with error handling
- Local Storage - Hive for local data persistence
- Component Library - Comprehensive reusable UI components (Atoms, Molecules, Organisms)
- Multi-Flavor - Development, Staging, and Production environments
- Error Tracking - Global error handling and monitoring
- Offline Support - Local caching with connectivity detection
This project follows Clean Architecture with three main layers:
βββββββββββββββββββββββββββββββββββββββββββββββ
β Presentation Layer β
β (Pages, Widgets, BLoCs, FormZ) β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βββββββββββββββββββΌββββββββββββββββββββββββββββ
β Domain Layer β
β (Entities, UseCases, Repository Interfaces)β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βββββββββββββββββββΌββββββββββββββββββββββββββββ
β Data Layer β
β (Models, Repositories, Data Sources) β
βββββββββββββββββββββββββββββββββββββββββββββββ
- Presentation: UI components, state management (BLoC), form validation (FormZ)
- Domain: Business logic, entities, use cases, repository contracts
- Data: API integration, local storage, repository implementations
lib/
βββ app/ # Application configuration
β βββ config.dart # App-wide configuration
β βββ flavor.dart # Environment flavors (dev, stag, prod)
β βββ locator.dart # Dependency injection setup
β βββ modules.dart # Module registration
β βββ app.dart # Root app widget
βββ core/ # Core functionality
β βββ components/ # UI component library
β β βββ atom/ # Basic building blocks (Text, Skeleton)
β β βββ molecule/ # Composite components (Buttons, Inputs)
β β βββ organism/ # Complex components (Cards, Pickers)
β βββ constants/ # App-wide constants
β βββ data/ # Core data utilities
β βββ exceptions/ # Custom exceptions
β βββ extensions/ # Dart/Flutter extensions
β βββ failures/ # Error handling
β βββ helpers/ # Helper functions
β βββ module/ # Module system base
β βββ networks/ # HTTP client configuration
β βββ pages/ # Common pages (Splash, Error)
β βββ preferences/ # Local storage
β βββ usecases/ # Base use case classes
β βββ utils/ # Utility functions
βββ features/ # Feature modules
β βββ auth/ # Authentication feature
β β βββ data/
β β β βββ models/
β β β βββ repositories/
β β β βββ sources/
β β βββ domain/
β β β βββ entities/
β β β βββ repositories/
β β β βββ usecases/
β β βββ presentation/
β β β βββ blocs/
β β β βββ formz/
β β β βββ pages/
β β β βββ widgets/
β β βββ module.dart
β βββ home/ # Home feature
β βββ settings/ # Settings feature
βββ l10n/ # Internationalization
β βββ app_en.arb
β βββ app_id.arb
βββ main_dev.dart # Dev environment entry point
main_prod.dart # Prod environment entry point
- Flutter SDK:
^3.10.0 - Dart SDK:
^3.10.0 - IDE: VS Code or Android Studio
-
Clone the repository
git clone <repository-url> cd flutter_boilerplate
-
Install dependencies
flutter pub get
-
Generate code
flutter pub run build_runner build --delete-conflicting-outputs
-
Run the app
# Development flutter run -t lib/main_dev.dart # Production flutter run -t lib/main_prod.dart
The app supports multiple environments configured in lib/app/config.dart:
static const FlavorConfig<String> baseUrl = FlavorConfig<String>(
prod: 'https://api.production.com',
dev: 'https://api.development.com',
stag: 'https://api.staging.com',
);Each feature is a self-contained module with its own routes and dependencies.
-
Create module structure
features/your_feature/ βββ data/ β βββ models/ β βββ repositories/ β βββ sources/ βββ domain/ β βββ entities/ β βββ repositories/ β βββ usecases/ βββ presentation/ β βββ blocs/ β βββ pages/ β βββ widgets/ βββ module.dart βββ your_feature.dart -
Implement module.dart
class YourFeatureModule implements BaseModule { @override Future<void> inject(GetIt getIt) async { // Register data sources getIt.registerLazySingleton<YourRemoteSource>( () => YourRemoteSourceImpl(getIt()), ); // Register repositories getIt.registerLazySingleton<YourRepository>( () => YourRepositoryImpl(getIt()), ); // Register use cases getIt.registerLazySingleton(() => GetYourDataUseCase(getIt())); // Register BLoCs getIt.registerFactory(() => YourBloc(getIt())); } @override Map<String, Route<dynamic>> routes(RouteSettings settings) { return { YourPage.routeName: MaterialPageRoute( builder: (_) => const YourPage(), settings: settings, ), }; } }
-
Register in app/modules.dart
var appModules = <BaseModule>[ AuthModule(), SettingsModule(), HomeModule(), YourFeatureModule(), // Add here ];
This project uses flutter_bloc for state management.
abstract class YourEvent extends Equatable {
const YourEvent();
@override
List<Object?> get props => [];
}
class LoadData extends YourEvent {
final String? filter;
const LoadData({this.filter});
@override
List<Object?> get props => [filter];
}enum YourStatus {
initial,
loading,
loaded,
error,
navigateToDetail,
}
class YourState extends Equatable {
final YourStatus status;
final List<YourModel> data;
final String? errorMessage;
const YourState({
this.status = YourStatus.initial,
this.data = const [],
this.errorMessage,
});
@override
List<Object?> get props => [status, data, errorMessage];
}class YourBloc extends Bloc<YourEvent, YourState> {
final GetYourDataUseCase _getDataUseCase;
YourBloc(this._getDataUseCase) : super(const YourState()) {
on<LoadData>(_onLoadData);
}
Future<void> _onLoadData(
LoadData event,
Emitter<YourState> emit,
) async {
emit(state.copyWith(status: YourStatus.loading));
final result = await _getDataUseCase(event.filter);
result.fold(
(failure) => emit(state.copyWith(
status: YourStatus.error,
errorMessage: failure.message,
)),
(data) => emit(state.copyWith(
status: YourStatus.loaded,
data: data,
)),
);
}
}class EmailInput extends FormzInput<String, EmailInputError> {
const EmailInput.pure() : super.pure('');
const EmailInput.dirty([String value = '']) : super.dirty(value);
static final _emailRegExp = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
@override
EmailInputError? validator(String value) {
if (value.isEmpty) return EmailInputError.empty;
if (!_emailRegExp.hasMatch(value)) return EmailInputError.invalid;
return null;
}
}The project includes a comprehensive component library following Atomic Design:
- Text Components:
HeadingText,RegularText,SubTitleText,TitleText - Loading:
Skeleton,SkeletonAnimation
- Buttons:
ArrowButton,MiniElevatedButton,MiniOutlinedButton,MiniIconButton,DropdownMenuButton - Inputs:
RegularInput,PasswordInput,SearchTextInput,PhoneTextInput,OtpTextInput,DropdownInput,EditableTextInput - Other:
RadioCircle,ContentSheet,InputLabel
- Cards:
CardShadow,CardTicket - Widgets:
ButtonWidget,SwitchWidget,EmptyWidget,LoadingComponent - Utilities:
SmartNetworkImage,BottomSheetImagePicker,DottedBorder,BlinkAnimation
import 'package:flutter_boilerplate/core/core.dart';
// Text
HeadingText('Welcome', fontSize: 24, fontWeight: FontWeight.bold)
// Button
ButtonWidget(
text: 'Submit',
onPressed: () {},
isLoading: false,
)
// Input
RegularInput(
label: 'Email',
onChanged: (value) {},
errorText: 'Invalid email',
)
// Card
CardShadow(
child: YourContent(),
shadowColor: Colors.grey,
)Follow these steps to add a new feature:
-
Create feature structure
mkdir -p lib/features/products/{data,domain,presentation}/{models,entities,blocs,pages} -
Define entities (domain/entities/)
class Product extends Equatable { final String id; final String name; final double price; const Product({required this.id, required this.name, required this.price}); @override List<Object?> get props => [id, name, price]; }
-
Create repository interface (domain/repositories/)
abstract class ProductRepository { Future<Either<Failure, List<Product>>> getProducts(); }
-
Implement use cases (domain/usecases/)
class GetProductsUseCase extends UseCase<List<Product>, NoParams> { final ProductRepository repository; GetProductsUseCase(this.repository); @override Future<Either<Failure, List<Product>>> call(NoParams params) { return repository.getProducts(); } }
-
Create data models (data/models/)
@JsonSerializable() class ProductModel { final String id; final String name; final double price; Product toEntity() => Product(id: id, name: name, price: price); }
-
Implement repository (data/repositories/)
class ProductRepositoryImpl implements ProductRepository { final ProductRemoteSource remoteSource; @override Future<Either<Failure, List<Product>>> getProducts() async { try { final result = await remoteSource.getProducts(); return Right(result.map((m) => m.toEntity()).toList()); } on ServerException catch (e) { return Left(ServerFailure(message: e.message)); } } }
-
Create BLoC (presentation/blocs/)
-
Build UI (presentation/pages/)
-
Register module (module.dart)
-
Add to app/modules.dart
Navigation is handled through the module system:
// Navigate to a route
Navigator.pushNamed(context, ProductDetailPage.routeName, arguments: {'id': productId});
// Pop
Navigator.pop(context);
// Replace
Navigator.pushReplacementNamed(context, HomePage.routeName);Add translations in lib/l10n/:
// app_en.arb
{
"welcome": "Welcome",
"login": "Login"
}
// app_id.arb
{
"welcome": "Selamat Datang",
"login": "Masuk"
}Use in code:
Text(context.l10n.welcome)All errors should use the Failure pattern:
result.fold(
(failure) {
// Handle error
if (failure is ServerFailure) {
// Network error
} else if (failure is CacheFailure) {
// Cache error
}
},
(data) {
// Handle success
},
);- Module Independence - Each feature module should be self-contained
- Clean Architecture - Maintain strict layer separation
- BLoC Pattern - All business logic goes in BLoCs, not widgets
- FormZ Validation - Use FormZ for all form validations
- Error Handling - Always use Either<Failure, Success> pattern
- Component Reuse - Use existing components before creating new ones
- Naming Conventions - Follow Dart naming conventions
- Documentation - Document complex logic and public APIs
- Testing - Write unit tests for business logic
- Code Generation - Run build_runner after model changes
- Use trailing commas for better formatting
- Keep functions small and focused
- Prefer composition over inheritance
- Use const constructors where possible
- Follow the DRY principle
# Run development build
flutter run -t lib/main_dev.dart
# Run production build
flutter run -t lib/main_prod.dart
# Generate code
flutter pub run build_runner build --delete-conflicting-outputs
# Watch for changes and generate code
flutter pub run build_runner watch --delete-conflicting-outputs
# Run tests
flutter test
# Analyze code
flutter analyze
# Format code
dart format lib/
# Clean build
flutter clean && flutter pub get# Run all tests
flutter test
# Run specific test file
flutter test test/features/auth/domain/usecases/login_usecase_test.dart
# Run with coverage
flutter test --coverage- flutter_bloc (^9.1.1) - State management
- get_it (^8.0.3) - Dependency injection
- dio (^5.8.0) - HTTP client
- dartz (^0.10.1) - Functional programming (Either, Option)
- formz (^0.8.0) - Form validation
- hive (^2.2.3) - Local storage
- equatable (^2.0.7) - Value equality
- json_annotation (^4.9.0) - JSON serialization
- cached_network_image (^3.4.1) - Image caching
- connectivity_plus (^6.1.4) - Network connectivity
- Create a feature branch from
develop - Follow the architecture and coding standards
- Write tests for new features
- Update documentation
- Create a pull request
This project is licensed under the MIT License.
For issues and questions:
- Check existing documentation
- Review similar implementations in existing features
- Consult the Copilot instructions in
.github/copilot-instructions.md
Happy Coding! π