Настройка архитектуры BLoC для Flutter-приложения
BLoC (Business Logic Component) — официально рекомендованный паттерн управления состоянием от команды Flutter. Основан на потоках событий и состояний: UI отправляет Event, BLoC обрабатывает и выдаёт State. Библиотека flutter_bloc от Felix Angelov стала стандартом в крупных Flutter-проектах.
Как работает BLoC на практике
// Events
abstract class ProfileEvent {}
class ProfileLoaded extends ProfileEvent {
final String userId;
ProfileLoaded(this.userId);
}
class ProfileRefreshed extends ProfileEvent {}
// States
abstract class ProfileState {}
class ProfileInitial extends ProfileState {}
class ProfileLoading extends ProfileState {}
class ProfileSuccess extends ProfileState {
final UserProfile profile;
ProfileSuccess(this.profile);
}
class ProfileFailure extends ProfileState {
final String error;
ProfileFailure(this.error);
}
// BLoC
class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
final UserRepository _repository;
ProfileBloc(this._repository) : super(ProfileInitial()) {
on<ProfileLoaded>(_onLoaded);
on<ProfileRefreshed>(_onRefreshed);
}
Future<void> _onLoaded(ProfileLoaded event, Emitter<ProfileState> emit) async {
emit(ProfileLoading());
try {
final profile = await _repository.getProfile(event.userId);
emit(ProfileSuccess(profile));
} catch (e) {
emit(ProfileFailure(e.toString()));
}
}
}
В виджете:
BlocBuilder<ProfileBloc, ProfileState>(
builder: (context, state) {
return switch (state) {
ProfileLoading() => const CircularProgressIndicator(),
ProfileSuccess(:final profile) => ProfileView(profile: profile),
ProfileFailure(:final error) => ErrorView(error: error),
_ => const SizedBox(),
};
},
)
BLoC vs Cubit
Cubit — упрощённая версия BLoC без Events. Методы Cubit вызываются напрямую: profileCubit.load(userId). Подходит для простых экранов. BLoC с Events даёт журнал событий и лучше тестируется при сложной логике с несколькими источниками событий.
Что настраиваем
Структура проекта: lib/features/profile/bloc/, data/, domain/. Подключение flutter_bloc, equatable (для правильного сравнения состояний). Регистрация BLoC-ов через MultiBlocProvider в корне приложения или через BlocProvider на уровне роута. Настройка BlocObserver для глобального логирования событий и ошибок.
Тестирование через bloc_test:
blocTest<ProfileBloc, ProfileState>(
'emits [Loading, Success] when ProfileLoaded is added',
build: () => ProfileBloc(mockRepository),
act: (bloc) => bloc.add(ProfileLoaded('user-123')),
expect: () => [ProfileLoading(), ProfileSuccess(tProfile)],
);
Сроки
Настройка BLoC-архитектуры с нуля: 2–3 дня. Рефакторинг setState-проекта: 1–2 недели. Стоимость — после анализа.







