CodeBlanks Logo Icon CodeBlanks

Cubit

Build a simple state class with Cubit.

Cubit

Cubit is the simpler class of the Bloc package. Instead of event classes, you call methods directly; you publish new state with emit.

class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);
  void increment() => emit(state + 1);
}

Cubit requires less code than Bloc for simple state.

Changing state with emit

Inside a Cubit, calling emit(newValue) publishes the new state. The state property gives the current state.

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

When emit is called, all listening widgets update.

Practice Build a counter with Cubit

Make SayacCubit extend Cubit<int>. Set initial state to 0 with super(0). The artir method should call emit(state + 1). In main, create a Cubit instance, call artir and print with print('deger: ${cubit.state}').

Starter code

main.dart
import 'package:flutter_bloc/flutter_bloc.dart';

// SayacCubit, Cubit<int>'ten türetilsin

void main() {
  final cubit = SayacCubit();
  cubit.artir();
  print('deger: ${cubit.state}');
}

Sample solution

main.dart
import 'package:flutter_bloc/flutter_bloc.dart';

class SayacCubit extends Cubit<int> {
  SayacCubit() : super(0);
  void artir() => emit(state + 1);
}

void main() {
  final cubit = SayacCubit();
  cubit.artir();
  print('deger: ${cubit.state}');
}

Expected output

deger: 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between Cubit and Bloc?

  • Does not publish state
  • Runs slower
  • Only works with StatelessWidget
  • Uses method calls instead of event classes Correct answer

Explanation: Cubit does not define event classes like Bloc; it changes state directly via method calls and publishes new state with emit.

2 Complete the emit call inside Cubit

Question
class SayacCubit extends Cubit<int> {
  SayacCubit() : super(0);
  void artir() => ____(state + 1);
}
Answer
class SayacCubit extends Cubit<int> {
  SayacCubit() : super(0);
  void artir() => emit(state + 1);
}

Explanation: In Cubit, emit is called to publish new state; this updates listening widgets.

3 Cubit parts

Term Meaning
Cubit Simple-state Bloc class
emit Method to publish new state
state Current state value
super(0) Initial state

All lessons in Intermediate