bloc
A predictable state management library that helps implement the BLoC design pattern
Top Related Projects
Reactive Programming in Swift
Cocoa framework and Obj-C dynamism bindings for ReactiveSwift.
Simple, scalable state management.
A JS library for predictable global state management
🗃️ Centralized State Management for Vue.js.
Quick Overview
Bloc is a predictable state management library for Dart and Flutter applications. It helps developers implement the Business Logic Component (BLoC) design pattern, separating the presentation layer from business logic and making it easier to manage complex application states.
Pros
- Promotes clean architecture and separation of concerns
- Highly testable due to its event-driven nature
- Extensive documentation and community support
- Integrates well with Flutter and supports code generation for reduced boilerplate
Cons
- Steep learning curve for beginners
- Can lead to verbose code for simple use cases
- Potential for overengineering in small projects
- Requires careful management of BLoCs to avoid memory leaks
Code Examples
- Creating a simple Cubit:
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
- Using a BLoC with events and states:
abstract 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));
}
}
- Consuming a BLoC in a Flutter widget:
BlocBuilder<CounterBloc, int>(
builder: (context, count) {
return Text('Count: $count');
},
)
Getting Started
To use Bloc in your Flutter project:
- Add the dependencies to your
pubspec.yaml
:
dependencies:
flutter_bloc: ^8.1.0
bloc: ^8.1.0
dev_dependencies:
bloc_test: ^9.1.0
- Import the package in your Dart file:
import 'package:flutter_bloc/flutter_bloc.dart';
- Create your first Cubit or BLoC, and use it in your widgets as shown in the code examples above.
Competitor Comparisons
Reactive Programming in Swift
Pros of RxSwift
- More mature and widely adopted in the iOS development community
- Offers a broader range of operators for complex data transformations
- Provides better integration with Apple's native frameworks
Cons of RxSwift
- Steeper learning curve due to its comprehensive nature
- Can lead to more complex and verbose code for simple use cases
- Requires careful management of subscriptions to avoid memory leaks
Code Comparison
RxSwift:
Observable.from([1, 2, 3, 4, 5])
.filter { $0 % 2 == 0 }
.map { $0 * 2 }
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
Bloc:
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<Increment>((event, emit) => emit(state + 1));
on<Decrement>((event, emit) => emit(state - 1));
}
}
Key Differences
- RxSwift focuses on reactive programming with observables, while Bloc emphasizes state management through events and states
- RxSwift offers more flexibility for complex data streams, whereas Bloc provides a more structured approach to handling application state
- RxSwift is Swift-specific, while Bloc is primarily used in Flutter/Dart applications
Cocoa framework and Obj-C dynamism bindings for ReactiveSwift.
Pros of ReactiveCocoa
- Mature and well-established framework with a large community
- Supports multiple programming paradigms (functional, reactive, imperative)
- Extensive documentation and learning resources available
Cons of ReactiveCocoa
- Steeper learning curve, especially for developers new to reactive programming
- Primarily focused on Apple platforms (iOS, macOS)
- Can lead to complex code for simple tasks if not used judiciously
Code Comparison
ReactiveCocoa:
let searchResults = searchText
.throttle(0.3, on: QueueScheduler.main)
.flatMap(.latest) { (query: String) -> SignalProducer<[SearchResult], NoError> in
return API.search(query)
}
Bloc:
class SearchBloc extends Bloc<SearchEvent, SearchState> {
SearchBloc() : super(SearchInitial()) {
on<SearchTextChanged>((event, emit) async {
final results = await API.search(event.query);
emit(SearchResultsLoaded(results));
});
}
}
The ReactiveCocoa example demonstrates its reactive nature with chained operations, while the Bloc example shows a more structured approach to handling state changes.
Simple, scalable state management.
Pros of MobX
- Simpler learning curve and less boilerplate code
- More flexible and less opinionated about application architecture
- Automatic tracking of observable state changes
Cons of MobX
- Less structured approach may lead to inconsistent code patterns
- Debugging can be more challenging due to automatic reactivity
- Potential performance issues with large, complex state trees
Code Comparison
MobX:
import { makeObservable, observable, action } from "mobx";
class Counter {
count = 0;
constructor() {
makeObservable(this, {
count: observable,
increment: action
});
}
increment() {
this.count++;
}
}
Bloc:
import 'package:bloc/bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
}
Summary
MobX offers a more flexible and less verbose approach to state management, with automatic tracking of observable changes. However, this flexibility can lead to less consistent code patterns and potential performance issues in complex applications. Bloc, on the other hand, provides a more structured and opinionated architecture, which can result in more consistent and maintainable code, but with a steeper learning curve and more boilerplate. The choice between the two depends on the specific needs of the project and the development team's preferences.
A JS library for predictable global state management
Pros of Redux
- More mature and widely adopted in the JavaScript ecosystem
- Extensive middleware ecosystem for additional functionality
- Simpler learning curve for developers familiar with JavaScript
Cons of Redux
- More boilerplate code required for setup and state management
- Can become complex in large applications with many actions and reducers
- Less opinionated, which may lead to inconsistent implementations across projects
Code Comparison
Redux:
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
};
Bloc:
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<IncrementEvent>((event, emit) => emit(state + 1));
on<DecrementEvent>((event, emit) => emit(state - 1));
}
}
The Redux example shows a reducer function handling state changes, while the Bloc example demonstrates a more structured approach with event handling and state emission. Bloc's code is more concise and type-safe, leveraging Dart's strong typing system. Redux requires more explicit action handling and switch statements, which can become verbose in larger applications.
🗃️ Centralized State Management for Vue.js.
Pros of Vuex
- Simpler learning curve for developers already familiar with Vue.js
- Tighter integration with Vue's reactivity system
- Built-in devtools for easier debugging and state inspection
Cons of Vuex
- Less structured approach to state management compared to BLoC
- Limited to Vue.js ecosystem, while BLoC is framework-agnostic
- Can become complex in large applications without careful organization
Code Comparison
Vuex:
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++ }
}
})
BLoC:
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<Increment>((event, emit) => emit(state + 1));
}
}
Both Vuex and BLoC provide state management solutions, but they differ in their approach and ecosystem. Vuex is tailored for Vue.js applications, offering seamless integration and reactivity. BLoC, on the other hand, provides a more structured pattern that can be used across different frameworks, making it particularly popular in the Flutter community. The choice between the two often depends on the specific project requirements and the development team's familiarity with the respective ecosystems.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
A predictable state management library that helps implement the BLoC design pattern.
Package | Pub |
---|---|
bloc | |
bloc_test | |
bloc_concurrency | |
bloc_lint | |
flutter_bloc | |
angular_bloc | |
hydrated_bloc | |
replay_bloc |
Sponsors
Our top sponsors are shown below! [Become a Sponsor]
Overview
The goal of this library is to make it easy to separate presentation from business logic, facilitating testability and reusability.
Documentation
- Official Documentation
- Bloc Package
- Bloc Test Package
- Bloc Concurrency Package
- Flutter Bloc Package
- Angular Bloc Package
- Hydrated Bloc Package
- Replay Bloc Package
Migration
Examples
Dart
- Counter - an example of how to create a
CounterBloc
(pure dart).
Flutter
- Counter - an example of how to create a
CounterBloc
to implement the classic Flutter Counter app. - Form Validation - an example of how to use the
bloc
andflutter_bloc
packages to implement form validation. - Bloc with Stream - an example of how to hook up a
bloc
to aStream
and update the UI in response to data from theStream
. - Complex List - an example of how to manage a list of items and asynchronously delete items one at a time using
bloc
andflutter_bloc
. - Infinite List - an example of how to use the
bloc
andflutter_bloc
packages to implement an infinite scrolling list. - Login Flow - an example of how to use the
bloc
andflutter_bloc
packages to implement a Login Flow. - Firebase Login - an example of how to use the
bloc
andflutter_bloc
packages to implement login via Firebase. - Github Search - an example of how to create a Github Search Application using the
bloc
andflutter_bloc
packages. - Weather - an example of how to create a Weather Application using the
bloc
andflutter_bloc
packages. The app uses aRefreshIndicator
to implement "pull-to-refresh" as well as dynamic theming. - Todos - an example of how to create a Todos Application using the
bloc
andflutter_bloc
packages. - Timer - an example of how to create a Timer using the
bloc
andflutter_bloc
packages. - Shopping Cart - an example of how to create a Shopping Cart Application using the
bloc
andflutter_bloc
packages based on flutter samples. - Dynamic Form - an example of how to use the
bloc
andflutter_bloc
packages to implement a dynamic form which pulls data from a repository. - Wizard - an example of how to build a multi-step wizard using the
bloc
andflutter_bloc
packages. - Fluttersaurus - an example of how to use the
bloc
andflutter_bloc
packages to create a thesaurus app -- made for Bytconf Flutter 2020. - I/O Photo Booth - an example of how to use the
bloc
andflutter_bloc
packages to create a virtual photo booth web app -- made for Google I/O 2021. - I/O Pinball - an example of how to use the
bloc
andflutter_bloc
packages to create a pinball web app -- made for Google I/O 2022. - I/O Holobooth - an example of how to use the
bloc
andflutter_bloc
packages to create a virtual photobooth experience -- made for Flutter Forward. - I/O Flip - an example of how to use the
bloc
,flutter_bloc
, andflame_bloc
packages to create a card game -- made for Google I/O 2023.
Web
- Counter - an example of how to use a
CounterBloc
in an AngularDart app. - Github Search - an example of how to create a Github Search Application using the
bloc
andangular_bloc
packages.
Flutter + Web
- Github Search - an example of how to create a Github Search Application and share code between Flutter and AngularDart.
Articles
- Bloc package - An intro to the bloc package with high level architecture and examples.
- Login tutorial with flutter_bloc - How to create a full login flow using the bloc and flutter_bloc packages.
- Unit testing with bloc - How to unit test the blocs created in the flutter login tutorial.
- Infinite list tutorial with flutter_bloc - How to create an infinite list using the bloc and flutter_bloc packages.
- Code sharing with bloc - How to share code between a mobile application written with Flutter and a web application written with AngularDart.
- Weather app tutorial with flutter_bloc - How to build a weather app which supports dynamic theming, pull-to-refresh, and interacting with a REST API using the bloc and flutter_bloc packages.
- Todos app tutorial with flutter_bloc - How to build a todos app using the bloc and flutter_bloc packages.
- Firebase login tutorial with flutter_bloc - How to create a fully functional login/sign up flow using the bloc and flutter_bloc packages with Firebase Authentication and Google Sign In.
- Flutter timer tutorial with flutter_bloc - How to create a timer app using the bloc and flutter_bloc packages.
- Firestore todos tutorial with flutter_bloc - How to create a todos app using the bloc and flutter_bloc packages that integrates with cloud firestore.
Books
- Flutter Complete Reference - A book about the Dart programming language (version 2.10, with null safety support) and the Flutter framework (version 1.20). It covers the bloc package (version 6.0.3) in all flavors: bloc, flutter_bloc hydrated_bloc, replay_bloc, bloc_test and cubit.
Extensions
- IntelliJ - extends IntelliJ/Android Studio with support for the Bloc library and provides tools for effectively creating Blocs for both Flutter and AngularDart apps.
- VSCode - extends VSCode with support for the Bloc library and provides tools for effectively creating Blocs for both Flutter and AngularDart apps.
Community
Learn more at the following links, which have been contributed by the community.
Packages
- Bloc.js - A port of the
bloc
state management library from Dart to JavaScript, by Felix Angelov. - Firebase Auth - A Web, Mobile Firebase Auth Plugin, by Rody Davis.
- Form Bloc - An easy way to create forms with BLoC pattern without writing a lot of boilerplate code, by Giancarlo.
- Flame Bloc - Bloc integration for the Flame game engine, by Flame Engine.
Video Tutorials
- Bloc Library: Basics and Beyond ð - Talk given at Flutter Europe about the basics of the bloc library, by Felix Angelov.
- Flutter Bloc Library Tutorial - Introduction to the Bloc Library, by Reso Coder.
- Flutter Youtube Search - How to build a Youtube Search app which interacts with an API using the bloc and flutter_bloc packages, by Reso Coder.
- Flutter Bloc - AUTOMATIC LOOKUP - v0.20 (and Up), Updated Tutorial - Updated Tutorial on the Flutter Bloc Package, by Reso Coder.
- Dynamic Theming with flutter_bloc - Tutorial on how to use the flutter_bloc package to implement dynamic theming, by Reso Coder.
- Persist Bloc State in Flutter - Tutorial on how to use the hydrated_bloc package to automatically persist app state, by Reso Coder.
- State Management Foundation - Introduction to state management using the flutter_bloc package, by Techie Blossom.
- Flutter Football Player Search - How to build a Football Player Search app which interacts with an API using the bloc and flutter_bloc packages, by Techie Blossom.
- Learning the Flutter Bloc Package - Learning the flutter_bloc package live, by Robert Brunhage
- Bloc Test Tutorial - Tutorial on how to unit test blocs using the bloc_test package, by Reso Coder.
- Bloc - from Zero to Hero - Playlist which includes everything needed to get started with bloc, by Flutterly.
- Bloc (Full Course, 11+ Hours) - Flutter State Management Course - 11+ hour video tutorial on Bloc and Flutter Bloc. In this video you will learn how to create fully fledged production-ready apps with Bloc and Firebase as your backend, by Vandad Nahavandipoor.
Written Resources
- DevonFw Flutter Guide - A guide on building structured & scalable applications with Flutter and BLoC, by Sebastian Faust
- Using Google´s Flutter Framework for the Development of a Large-Scale Reference Application - Scientific paper describing how to build a large-scale Flutter application with BLoC, by Sebastian Faust
Extensions
- Feature Scaffolding for VSCode - A VSCode extension inspired by Reso Coder's clean architecture tutorials, which helps quickly scaffold features, by Kiritchouk Clément.
Maintainers
Top Related Projects
Reactive Programming in Swift
Cocoa framework and Obj-C dynamism bindings for ReactiveSwift.
Simple, scalable state management.
A JS library for predictable global state management
🗃️ Centralized State Management for Vue.js.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot