Flutter
Summary - Bloc basics
Combine Cubit, BlocProvider and BlocBuilder to make a counter.
Summary - Bloc basics
In this section you learned three things: with Cubit you do simple state management; with BlocProvider you provide the Cubit to the tree; with BlocBuilder you listen to state and redraw the UI.
BlocProvider<CounterCubit>(
create: (_) => CounterCubit(),
child: BlocBuilder<CounterCubit, int>(
builder: (context, state) => Text('$state'),
),
)
Combining these, you build a counter screen.
Exercise Build a counter screen
Make SayacCubit extend Cubit<int>, with an artir method calling emit(state + 1). Wrap the root with BlocProvider<SayacCubit>. In Ekrani, display the state with BlocBuilder<SayacCubit, int> and call context.read<SayacCubit>().artir() on the button. In main, call print('sayaç açıldı').
Show example solution
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SayacCubit extends Cubit<int> {
SayacCubit() : super(0);
void artir() => emit(state + 1);
}
void main() {
print('sayaç açıldı');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider<SayacCubit>(
create: (_) => SayacCubit(),
child: MaterialApp(home: Ekrani()),
);
}
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: BlocBuilder<SayacCubit, int>(
builder: (context, state) => Text('$state'),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<SayacCubit>().artir(),
child: Icon(Icons.add),
),
);
}
}
Test yourself
-
Which widget is used to display the Cubit's state on the counter screen?
- Scaffold
- AppBar
- StatelessWidget
- BlocBuilder
Show answer
BlocBuilder — BlocBuilder is used to display the Cubit's state; its builder function returns a widget based on the state.
-
Set the Cubit's initial state
class SayacCubit extends Cubit<int> {
SayacCubit() : ____;
void artir() => emit(state + 1);
}
Show answer
class SayacCubit extends Cubit<int> {
SayacCubit() : super(0);
void artir() => emit(state + 1);
}
-
Bloc basic parts
- Cubit
- Class managing simple state
- BlocProvider
- Provides Cubit to the tree
- BlocBuilder
- Listens state and redraws UI
- emit
- Method to publish new state
Next lesson: What is FutureBuilder?