Giải thích về Bloc Pattern trong Flutter?
Giải thích về Bloc Pattern trong Flutter?
BLoC (Business Logic Component) là pattern tách logic nghiệp vụ khỏi UI: UI gửi event vào BLoC, BLoC xử lý (gọi repository, API) rồi phát ra state mới, UI chỉ việc vẽ theo state. Pattern được giới thiệu tại Google I/O 2018, nhưng trong thực tế hầu hết dự án dùng package flutter_bloc (thư viện cộng đồng, do Felix Angelov duy trì), không tự viết bằng StreamController.
UI ──event──▶ Bloc ──(repository/API)──▶ Bloc ──state──▶ UI
flutter_bloc// event
sealed class CounterEvent {}
final class Increment extends CounterEvent {}
// bloc
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<Increment>((event, emit) => emit(state + 1));
}
}
// UI
BlocProvider(
create: (_) => CounterBloc(),
child: BlocBuilder<CounterBloc, int>(
builder: (context, count) => TextButton(
onPressed: () => context.read<CounterBloc>().add(Increment()),
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.