Convert Figma logo to code with AI

felangel logobloc

A predictable state management library that helps implement the BLoC design pattern

11,696
3,379
11,696
85

Top Related Projects

24,320

Reactive Programming in Swift

Cocoa framework and Obj-C dynamism bindings for ReactiveSwift.

27,458

Simple, scalable state management.

60,792

A JS library for predictable global state management

28,416

🗃️ 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

  1. Creating a simple Cubit:
class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);

  void increment() => emit(state + 1);
  void decrement() => emit(state - 1);
}
  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));
  }
}
  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:

  1. Add the dependencies to your pubspec.yaml:
dependencies:
  flutter_bloc: ^8.1.0
  bloc: ^8.1.0

dev_dependencies:
  bloc_test: ^9.1.0
  1. Import the package in your Dart file:
import 'package:flutter_bloc/flutter_bloc.dart';
  1. Create your first Cubit or BLoC, and use it in your widgets as shown in the code examples above.

Competitor Comparisons

24,320

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.

27,458

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.

60,792

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.

28,416

🗃️ 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 Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Bloc

build codecov Star on Github Flutter Website Awesome Flutter Flutter Samples License: MIT Discord Bloc Library


A predictable state management library that helps implement the BLoC design pattern.

PackagePub
blocpub package
bloc_testpub package
bloc_concurrencypub package
flutter_blocpub package
angular_blocpub package
hydrated_blocpub package
replay_blocpub package

Sponsors

Our top sponsors are shown below! [Become a Sponsor]


Overview

Bloc Architecture

The goal of this library is to make it easy to separate presentation from business logic, facilitating testability and reusability.

Documentation

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 and flutter_bloc packages to implement form validation.
  • Bloc with Stream - an example of how to hook up a bloc to a Stream and update the UI in response to data from the Stream.
  • Complex List - an example of how to manage a list of items and asynchronously delete items one at a time using bloc and flutter_bloc.
  • Infinite List - an example of how to use the bloc and flutter_bloc packages to implement an infinite scrolling list.
  • Login Flow - an example of how to use the bloc and flutter_bloc packages to implement a Login Flow.
  • Firebase Login - an example of how to use the bloc and flutter_bloc packages to implement login via Firebase.
  • Github Search - an example of how to create a Github Search Application using the bloc and flutter_bloc packages.
  • Weather - an example of how to create a Weather Application using the bloc and flutter_bloc packages. The app uses a RefreshIndicator to implement "pull-to-refresh" as well as dynamic theming.
  • Todos - an example of how to create a Todos Application using the bloc and flutter_bloc packages.
  • Timer - an example of how to create a Timer using the bloc and flutter_bloc packages.
  • Shopping Cart - an example of how to create a Shopping Cart Application using the bloc and flutter_bloc packages based on flutter samples.
  • Dynamic Form - an example of how to use the bloc and flutter_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 and flutter_bloc packages.
  • Fluttersaurus - an example of how to use the bloc and flutter_bloc packages to create a thesaurus app -- made for Bytconf Flutter 2020.
  • I/O Photo Booth - an example of how to use the bloc and flutter_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 and flutter_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 and flutter_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, and flame_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 and angular_bloc packages.

Flutter + Web

  • Github Search - an example of how to create a Github Search Application and share code between Flutter and AngularDart.

Articles

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

Video Tutorials

Written Resources

Extensions

Maintainers

NPM DownloadsLast 30 Days