FolderStructure.dev

Flutter BLoC Project Structure

BLoC pattern with flutter_bloc. Event-driven state management with clear separation of concerns.

#flutter #dart #mobile #bloc #state-management
PNGPDF

Project Directory

myapp/
pubspec.yaml
pubspec.lock
analysis_options.yaml
.gitignore
lib/
main.dart
MultiBlocProvider setup
app.dart
core/
constants/
theme/
blocs/
App-wide blocs
app_bloc_observer.dart
Debug observer
features/
auth/
bloc/
Feature BLoC
auth_bloc.dart
auth_event.dart
auth_state.dart
data/
auth_repository.dart
user_model.dart
screens/
login_screen.dart
widgets/
home/
bloc/
data/
screens/
widgets/
shared/
widgets/
models/
routing/
app_router.dart
test/
features/
auth/
bloc/
bloc_test tests
android/
ios/
assets/

Why This Structure?

BLoC (Business Logic Component) enforces strict separation between UI and logic. Events go in, states come out. Highly testable with bloc_test package. Predictable state changes through the event-driven pattern.

Key Directories

  • lib/features/*/bloc/-BLoC, events, and states per feature
  • *_bloc.dart-Handles events, emits states
  • *_event.dart-User actions as sealed classes
  • *_state.dart-UI states as sealed classes

BLoC Event Handler

// lib/features/auth/bloc/auth_bloc.dart
class AuthBloc extends Bloc {
  final AuthRepository _authRepository;

  AuthBloc(this._authRepository) : super(AuthInitial()) {
    on(_onLoginRequested);
  }

  Future _onLoginRequested(
    LoginRequested event, Emitter emit
  ) async {
    emit(AuthLoading());
    try {
      final user = await _authRepository.login(event.email, event.password);
      emit(AuthSuccess(user));
    } catch (e) {
      emit(AuthFailure(e.toString()));
    }
  }
}

Getting Started

  1. flutter pub add flutter_bloc equatable
  2. flutter pub add -d bloc_test
  3. Create feature with bloc/, screens/, widgets/
  4. Provide BLoC via BlocProvider
  5. Consume with BlocBuilder/BlocConsumer

When To Use This

  • Need strict separation of concerns
  • Want excellent testability with bloc_test
  • Team prefers explicit event-driven architecture
  • Complex UI state transitions
  • Large apps with many state changes

Trade-offs

  • Boilerplate-Event, state, and bloc files per feature
  • Learning curve-Streams and event-driven thinking required
  • Verbosity-More code than simpler solutions