bloc_signals_flutter

⚡ bloc_signals_flutter

"With the rigor of BLoC and the flex and speed of Signals"

Flutter extensions, UI widgets, dependency injection providers, and reactive bindings for the bloc_signals state management library.

This companion package provides BlocSignalProvider, MultiBlocSignalProvider, BlocSignalBuilder, BlocSignalListener, BlocSignalConsumer, BlocSignalSelector, BuildContext extensions (read(), watch()), and Flutter Listenable interop helpers.


🌐 Ecosystem Packages

The BlocSignal monorepo consists of 14 modular packages:

Package Version Description
bloc_signals pub Core pure Dart reactive state primitives bridging BLoC & Signals
bloc_signals_flutter pub Flutter UI bindings, providers, builders, listeners & selectors
bloc_signals_bloc pub Classic BLoC 8/9 interop adapters & bidirectional event bridges
bloc_signals_riverpod pub Bidirectional Riverpod 2/3 interop adapters & provider extensions
bloc_signals_jaspr pub Jaspr web component integration and state binding for BlocSignal
bloc_signals_hydrate pub Automated synchronous local state persistence & hydration
bloc_signals_replay pub Undo & redo state history tracking for CubitSignal and BlocSignal
bloc_signals_otel pub OpenTelemetry tracing and span generation for state transitions
bloc_signals_devtools pub Universal DevTools telemetry observer using dart:developer
bloc_signals_test pub Declarative unit testing utilities (blocSignalTest)
bloc_signals_lint pub Custom analyzer lint rules & automated IDE quick-fixes
bloc_signals_genui pub Pure-Dart A2UI streaming state machine & Generative UI runtime adapter
bloc_signals_genui_flutter pub Declarative Flutter surface containers & A2UI catalog widget adapters
bloc_signals_genui_jaspr pub Declarative Jaspr web components & DOM catalog adapters for A2UI

⚡ Key Features

  • 📦 BlocSignalProvider: Dependency injection InheritedWidget with automatic container disposal on unmount.
  • 🔗 MultiBlocSignalProvider: Nesting-free multi-bloc provider wrapper.
  • ⚡ BlocSignalBuilder: Fine-grained reactive UI widget triggered synchronously on state changes.
  • 👂 BlocSignalListener: Side-effect listener widget for snackbars, dialogs, and navigation.
  • 🔀 BlocSignalConsumer: Combines builder and listener into a single widget.
  • 🔍 BlocSignalSelector: Rebuilds ONLY when a derived state slice changes.

🚀 Getting Started

Add bloc_signals_flutter to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  bloc_signals_flutter: ^1.6.0

💡 Quick Examples

1. Providing & Building (BlocSignalProvider & BlocSignalBuilder)

import 'package:flutter/material.dart';
import 'package:bloc_signals_flutter/bloc_signals_flutter.dart';

void main() {
  runApp(
    MaterialApp(
      home: BlocSignalProvider(
        create: (context) => CounterBloc(),
        child: const CounterScreen(),
      ),
    ),
  );
}

class CounterScreen extends StatelessWidget {
  const CounterScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('BlocSignal Counter')),
      body: Center(
        child: BlocSignalBuilder<CounterBloc, int>(
          builder: (context, state) => Text('Count: $state'),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context.read<CounterBloc>().add(Increment()),
        child: const Icon(Icons.add),
      ),
    );
  }
}

To avoid rebuilding an expensive static subtree on every state emission, use the .child constructor (BlocSignalBuilder.child, BlocSignalConsumer.child, or BlocSignalSelector.child):

BlocSignalBuilder<CounterBloc, int>.child(
  child: const ExpensiveStaticHeader(),
  builder: (context, state, child) {
    return Column(
      children: [
        if (child != null) child,
        Text('Count: $state'),
      ],
    );
  },
)

For inline reactive widgets on any ReadonlySignal (including Signal and Computed) or BlocSignalBase (CubitSignal and BlocSignal), use the zero-allocation .build and .build.child extensions:

// Direct signal or container builder:
counterSignal.build((context, value) => Text('Count: $value'))

// With static child preservation:
counterCubit.build.child(
  const ExpensiveStaticHeader(),
  (context, state, child) => Column(
    children: [
      if (child != null) child,
      Text('Count: $state'),
    ],
  ),
)

For routes or tabs that unmount briefly and remount, pass retentionPeriod: to BlocSignalProvider to keep the created container alive for a grace period (call BlocSignalProvider.clearRetained() in tests or at logout boundaries):

BlocSignalProvider<SearchBloc>(
  create: (_) => SearchBloc(),
  retentionPeriod: const Duration(seconds: 30),
  child: const SearchPage(),
)

2. Side-Effect Listener (BlocSignalListener)

BlocSignalListener<AuthBloc, AuthState>(
  listener: (context, state) {
    if (state is AuthFailure) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(state.error)),
      );
    }
  },
  child: const LoginForm(),
)

Use take and takeWhile on BlocSignalListener (default, .debounce, .throttle, and .transition) to cap listener execution automatically, or use .debounce / .throttle for rate-limited side effects and .transition when you need both (context, previous, current) states:

// Rate-limited listener (trailing-edge debounce or leading-edge throttle):
BlocSignalListener<SearchCubit, String>.debounce(
  duration: const Duration(milliseconds: 300),
  listener: (context, query) => analytics.logSearch(query),
  child: const SearchResults(),
)

// Transition-aware listener receiving both previous and current states:
BlocSignalListener<AuthBloc, AuthState>.transition(
  listener: (context, previous, current) {
    if (previous is AuthLoading && current is AuthFailure) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(current.error)),
      );
    }
  },
  child: const LoginForm(),
)

One-shot take with listenWhen:

BlocSignalListener<AuthBloc, AuthState>(
  take: 1,
  listenWhen: (_, current) => current is AuthSuccess,
  listener: (context, state) {
    Navigator.of(context).pushReplacementNamed('/home');
  },
  child: const LoginForm(),
)

Predicate-bounded takeWhile (without listenWhen shadowing the terminating state):

BlocSignalListener<AuthBloc, AuthState>(
  takeWhile: (current) => current is! AuthLoggedOut,
  listener: (context, state) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Auth update: $state')),
    );
  },
  child: const DashboardView(),
)

Quota runtime semantics:

  • listenWhen and rate-limiting (debounce / throttle) filter emissions before quota evaluation.
  • takeWhile(current) is evaluated before incrementing the invocation count; returning false permanently detaches the listener without calling listener.
  • take increments and detaches synchronously before invoking listener (preventing reentrant over-fires); take: 0 skips effect registration entirely.
  • Swapping bloc resets counters; takeWhile detachment persists across widget rebuilds unless takeWhile becomes null or bloc swaps.

3. Combined Consumer (BlocSignalConsumer)

BlocSignalConsumer<CartBloc, CartState>(
  listener: (context, state) {
    if (state.itemAdded) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Item added to cart!')),
      );
    }
  },
  builder: (context, state) {
    return Text('Cart items: ${state.items.length}');
  },
)

BlocSignalConsumer (default, .transition, and .child) also supports take and takeWhile with the same filtering, synchronous detachment, and bloc-swap / rebuild semantics. Quotas cap only listener while builder continues rebuilding on every state emission (subject to buildWhen):

BlocSignalConsumer<CartBloc, CartState>.child(
  take: 1,
  listenWhen: (_, current) => current.isCheckoutReady,
  listener: (context, state) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Ready to check out!')),
    );
  },
  child: const CartHeaderBanner(),
  builder: (context, state, child) {
    return Column(
      children: [
        if (child != null) child,
        Text('Cart items: ${state.items.length}'),
      ],
    );
  },
)

4. Selective Rebuilds (BlocSignalSelector & context.select)

BlocSignalSelector<UserBloc, UserState, String>(
  selector: (state) => state.username, // Rebuilds ONLY if username changes
  options: ComputedOptions(name: 'UsernameSelector'), // Optional debug name
  builder: (context, username) {
    return Text('Hello, $username!');
  },
)

Or directly via BuildContext (with optional custom equals: comparator):

final canSubmit = context.select<FormCubit, bool>(
  (cubit) => cubit.stateValue.canSubmit,
);

// Optional lookups that return null instead of throwing BlocSignalProviderNotFoundError:
final analytics = context.maybeRead<AnalyticsCubit>();
final theme = context.maybeWatch<ThemeCubit>();

5. Reactive State & Signal Access (context.value & context.state)

To subscribe directly to state emissions inside widget build() methods:

@override
Widget build(BuildContext context) {
  // Rebuilds this element whenever CounterCubit emits a new state value:
  final count = context.value<CounterCubit, int>();

  return Text('Count: $count');
}

To look up the underlying ReadonlySignal<S> without registering an element rebuild dependency (for composing signals via computed() or effect()):

// Looks up the container signal without registering an element rebuild dependency:
final counterSignal = context.state<CounterCubit, int>();

// Composes reactively in signals:
final isEven = computed(() => counterSignal.value.isEven);

Tip

Generic Type Parameters for context.select: Unlike Riverpod's 3-parameter context.select or package:flutter_bloc, BlocSignal's context.select takes 2 generic type parameters:

  1. B: The BlocSignalBase container type (for example UserCubit or CounterBloc)
  2. R: The selected return value type (for example String or bool)

The callback receives the bloc instance directly: context.select<FormCubit, bool>((cubit) => cubit.stateValue.canSubmit).

6. MultiBlocSignalProvider

MultiBlocSignalProvider(
  providers: [
    BlocSignalProvider<AuthBloc>(create: (context) => AuthBloc()),
    BlocSignalProvider<ThemeBloc>(create: (context) => ThemeBloc()),
  ],
  child: const AppShell(),
)

7. Flutter Listenable & ChangeNotifier Interop

// Convert any ChangeNotifier into a CubitSignal
final ChangeNotifier notifier = MyChangeNotifier();
final cubit = notifier.toBlocSignal(readState: () => notifier.count);

// Convert any CubitSignal into a Flutter ValueListenable.
// Lazily subscribes when the first listener is added and automatically
// unsubscribes when the last listener is removed:
final ValueListenable<int> listenable = cubit.toValueListenable();

🤖 AI Coding Assistant Skill & Guides

This package is supported by official pre-packaged AI Coding Skills and architectural documentation guides representing Flutter widget lifecycle patterns, UI binding rules, and migration paths for BlocSignal:

  • 🔄 Migration Guide: Transitioning from classic package:flutter_bloc / package:bloc to BlocSignal.
  • 🌁 Universal Interoperability Guide: Bridging state containers across BLoC, Riverpod, Provider, and Listenable primitives.
  • 📦 AI Skill Bundle: Load the pre-packaged bloc-signals skill bundle for AI coding assistants (such as Claude Code, Antigravity, Gemini, Cursor, or Codex) to guide code generation and analysis.

📜 Credits & Acknowledgements

Inspired by flutter_bloc by Felix Angelov and signals_flutter by Rody Davis.

Libraries

bloc_signals_flutter
Flutter bindings and UI integrations for the reactive BlocSignal library.