0Pricing
Flutter Mobile Development · 강의

이벤트, 상태 및 Cubit과 Bloc 중 선택하기

Cubit과 Bloc 중 적합한 방식을 선택하고 이벤트에서 상태로 이어지는 변환을 깔끔하게 설계합니다.

이벤트, 상태 및 Cubit과 Bloc 중 선택하기은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Two Tools, One Family

The flutter_bloc package ships two state-management primitives: Cubit and Bloc. Both extend the same base class and both emit a stream of states to your UI.

  • Cubit exposes plain methods you call directly (e.g. increment()).
  • Bloc reacts to events you add (e.g. add(IncrementPressed())) and maps them to states.

This lesson teaches you how each one transforms input into State, and how to pick the right one for a given feature.

Cubit: Methods to States

A Cubit is the simpler primitive. You extend Cubit<T>, pass an initial state to super(...), and call emit(newState) inside methods to push a new state to listeners.

There is no event object and no mapping layer. The method is the API surface.

import 'package:flutter_bloc/flutter_bloc.dart';

class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);

  void increment() => emit(state + 1);
  void decrement() => emit(state - 1);
  void reset() => emit(0);
}

Bloc: Events to States

A Bloc separates the intent (an event) from the logic (a handler). You define event classes, then register handlers with on<Event> in the constructor. The UI never calls logic directly; it only adds events.

This indirection costs more boilerplate but gives you a single, traceable funnel for every state change.

import 'package:flutter_bloc/flutter_bloc.dart';

sealed class CounterEvent {}

class IncrementPressed extends CounterEvent {}
class DecrementPressed extends CounterEvent {}

class CounterBloc extends Bloc<CounterEvent, int> {
  CounterBloc() : super(0) {
    on<IncrementPressed>((event, emit) => emit(state + 1));
    on<DecrementPressed>((event, emit) => emit(state - 1));
  }
}

Modeling States Explicitly

A plain int works for a counter, but real features have multiple shapes: loading, success, failure. Model these as a sealed class hierarchy so the compiler forces your UI to handle every case.

  • Sealed classes enable exhaustive switch in Dart 3.
  • Each state carries only the data valid for that phase.
sealed class ProfileState {
  const ProfileState();
}

class ProfileLoading extends ProfileState {
  const ProfileLoading();
}

class ProfileLoaded extends ProfileState {
  final String name;
  const ProfileLoaded(this.name);
}

class ProfileError extends ProfileState {
  final String message;
  const ProfileError(this.message);
}

void main() {
  final ProfileState s = ProfileLoaded('Ada');
  final label = switch (s) {
    ProfileLoading() => 'Loading...',
    ProfileLoaded(:final name) => 'Hello, $name',
    ProfileError(:final message) => 'Error: $message',
  };
  print(label);
}

Equatable: Avoiding Redundant Rebuilds

Bloc and Cubit only notify listeners when the new state is not equal to the previous one. By default Dart objects compare by identity, so two distinct instances with the same data are treated as different and trigger a rebuild.

Override equality (commonly with the equatable package) so value-equal states are deduplicated and your widgets stop rebuilding needlessly.

import 'package:equatable/equatable.dart';

class CartState extends Equatable {
  final int itemCount;
  final double total;
  const CartState(this.itemCount, this.total);

  @override
  List<Object?> get props => [itemCount, total];
}

// emit(CartState(2, 19.98)) twice in a row notifies listeners only once.

Async Work Inside a Handler

Most real handlers are asynchronous: fetch data, then emit. With a Bloc you can emit multiple times from one handler — first a loading state, then success or failure.

The handler signature gives you an emit callback rather than a return value precisely so you can stream several states during one event.

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  final ProfileRepo repo;
  ProfileBloc(this.repo) : super(const ProfileLoading()) {
    on<ProfileRequested>((event, emit) async {
      emit(const ProfileLoading());
      try {
        final name = await repo.fetchName(event.id);
        emit(ProfileLoaded(name));
      } catch (e) {
        emit(ProfileError(e.toString()));
      }
    });
  }
}

Event Transformers: The Bloc-Only Superpower

This is the feature that most often decides the question. With a Bloc you control how concurrent events are processed by passing a transformer to on<Event> (from the bloc_concurrency package):

  • concurrent() — handle all events in parallel (default).
  • sequential() — one at a time, in order.
  • droppable() — ignore new events while one is running (great for buttons).
  • restartable() — cancel the in-flight handler when a newer event arrives (great for search).

Cubit has no event stream, so it cannot do this without writing the debounce/throttle logic by hand.

import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:stream_transform/stream_transform.dart';

EventTransformer<E> debounce<E>(Duration d) {
  return (events, mapper) => events.debounce(d).switchMap(mapper);
}

class SearchBloc extends Bloc<SearchEvent, SearchState> {
  SearchBloc() : super(const SearchInitial()) {
    on<QueryChanged>(
      _onQueryChanged,
      transformer: debounce(const Duration(milliseconds: 300)),
    );
  }

  Future<void> _onQueryChanged(QueryChanged e, Emitter emit) async {
    // runs at most once per 300ms of typing
  }
}

Observing Transitions for Debugging

Because a Bloc funnels every change through events, it can report a full Transition: the current state, the triggering event, and the next state. Override onTransition (or use a global BlocObserver) to log this funnel.

A Cubit only sees Change (current and next state) — there is no event to log, because there is no event. This is why Bloc is favored for features that need an audit trail.

import 'package:flutter_bloc/flutter_bloc.dart';

class AppObserver extends BlocObserver {
  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print('${bloc.runtimeType}: ${transition.event} '
        '=> ${transition.nextState}');
  }
}

void main() {
  Bloc.observer = AppObserver();
}

The Decision Rule

A practical heuristic the Bloc maintainers themselves recommend: start with a Cubit and reach for a Bloc only when you need what a Bloc adds.

Choose Cubit when:

  • The logic is simple direct method calls (toggles, counters, form fields).
  • You do not need to debounce/throttle/drop concurrent inputs.
  • You value less boilerplate and easier onboarding.

Choose Bloc when:

  • You need event transformers (debounce search, droppable submit).
  • You want a traceable event log for analytics or debugging.
  • Many distinct inputs map to one feature and you want them documented as event types.

Same Feature, Both Ways

Compare a toggle written as a Cubit versus a Bloc. The Cubit is shorter and reads top-to-bottom; the Bloc adds an event type and a handler. For a pure toggle, the Cubit is the better choice — the Bloc machinery buys you nothing here.

// Cubit version
class ThemeCubit extends Cubit<bool> {
  ThemeCubit() : super(false);
  void toggle() => emit(!state);
}

// Bloc version (same behavior, more ceremony)
sealed class ThemeEvent {}
class ThemeToggled extends ThemeEvent {}

class ThemeBloc extends Bloc<ThemeEvent, bool> {
  ThemeBloc() : super(false) {
    on<ThemeToggled>((e, emit) => emit(!state));
  }
}

Designing Clean Event-to-State Transformations

Whichever you pick, keep transformations clean:

  • States are immutable; use copyWith to derive the next state instead of mutating.
  • One event (or method) should map to a coherent set of emitted states, never to UI navigation or side effects you cannot trace.
  • Keep I/O in a repository; the Bloc/Cubit only orchestrates and emits.
class FormState {
  final String email;
  final bool submitting;
  const FormState({this.email = '', this.submitting = false});

  FormState copyWith({String? email, bool? submitting}) => FormState(
        email: email ?? this.email,
        submitting: submitting ?? this.submitting,
      );
}

void main() {
  const start = FormState();
  final next = start.copyWith(submitting: true);
  print('${next.email}|${next.submitting}'); // |true
}

Quick Check

A search field must issue a network request as the user types, but only after they pause for 300ms, cancelling any in-flight request when a newer keystroke arrives. Which choice best fits and why?

Recap

You learned how each primitive turns input into state and how to choose:

  • Cubit = methods call emit directly. Less boilerplate; ideal for toggles, counters, and simple forms.
  • Bloc = events are added and mapped via on<Event>. Buys you event transformers (debounce/throttle/droppable/restartable) and a traceable Transition log.
  • Model states as sealed, immutable classes; use Equatable to dedupe rebuilds and copyWith to derive next states.
  • Rule of thumb: start with a Cubit; upgrade to a Bloc only when you need concurrency control or an event audit trail.

자주 묻는 질문

“이벤트, 상태 및 Cubit과 Bloc 중 선택하기” 강의는 무료인가요?

네 — “이벤트, 상태 및 Cubit과 Bloc 중 선택하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“이벤트, 상태 및 Cubit과 Bloc 중 선택하기”에서 뭘 배우나요?

Cubit과 Bloc 중 적합한 방식을 선택하고 이벤트에서 상태로 이어지는 변환을 깔끔하게 설계합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“이벤트, 상태 및 Cubit과 Bloc 중 선택하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 이벤트, 상태 및 Cubit과 Bloc 중 선택하기
  2. BLoC의 스트림 변환기 및 이벤트 디바운싱
  3. HydratedBloc을 활용한 상태 저장
  4. bloc_test 및 Mocktail을 활용한 BLoC 테스트
← Flutter Mobile Development(으)로 돌아가기