neuron library

Neuron - Signal/Slot State Management for Flutter

═══════════════════════════════════════════════════════════════════════════════

Neuron is a powerful, elegant reactive state management library built around the Signal/Slot pattern. Write clean, maintainable Flutter apps with minimal boilerplate.

Philosophy

"Write less, do more, stay reactive."

  • Signal: A reactive value container that notifies when changed
  • Slot: A widget that rebuilds when connected signal emits
  • Controller: Business logic with auto-disposed signals

Why Neuron?

  • Clean Syntax: signal(), computed(), $() factory methods
  • StatelessWidget Only: No boilerplate, just reactive bindings
  • Auto-disposal: Signals disposed with controllers
  • Type-safe: Full Dart 3 pattern matching support
  • Feature-rich: Persistence, middleware, DevTools, animations

Quick Start

Step 1: Create a Controller

class CounterController extends NeuronController {
  // Choose your syntax:
  // late final count = Signal<int>(0).bind(this);  // Verbose
  late final count = signal(0);                     // Clean (recommended)
  // late final count = $(0);                       // Ultra-short

  // Computed values auto-track dependencies
  late final doubled = computed(() => count.val * 2);
  late final isEven = computed(() => count.val % 2 == 0);

  void increment() => count.emit(count.val + 1);

  // Singleton pattern for DI
  static CounterController get init =>
      Neuron.ensure<CounterController>(() => CounterController());
}

Step 2: Connect to UI

class CounterPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final c = CounterController.init;  // Get or create controller

    return Scaffold(
      body: Column(
        children: [
          // Signal → Slot binding
          Slot<int>(
            connect: c.count,
            to: (ctx, val) => Text('Count: $val'),
          ),
          Slot<int>(
            connect: c.doubled,
            to: (ctx, val) => Text('Doubled: $val'),
          ),
          ElevatedButton(
            onPressed: c.increment,
            child: Text('Increment'),
          ),
        ],
      ),
    );
  }
}

Step 3: Run App

void main() {
  runApp(NeuronApp(home: CounterPage()));
}

Feature Overview

Signal Types

Type Description
Signal<T> Core reactive value
AsyncSignal<T> Async operations (loading/data/error)
Computed<T> Derived values with auto-tracking
ListSignal<E> Reactive list with mutation methods
MapSignal<K,V> Reactive map
SetSignal<E> Reactive set
UndoableSignal Undo/redo support
FormSignal<T> Form fields with validation

Slot Widgets

Widget Description
Slot<T> Basic signal-to-widget binding
AsyncSlot<T> Async signal with loading/error states
AnimatedSlot<T> Auto-animated value transitions
SpringSlot<T> Physics-based spring animations
MorphSlot<T> Smooth widget morphing
PulseSlot<T> Attention-grabbing pulse effects
ShimmerSlot<T> Loading shimmer animations
MultiSlot Combine 2-6 signals (type-safe)

Rate Limiting

  • DebouncedSignal - Delay until quiet period
  • ThrottledSignal - Limit emission frequency
  • DistinctSignal - Filter duplicate values

Middleware & Persistence

  • LoggingMiddleware - Log value changes
  • ValidationMiddleware - Validate before emit
  • PersistentSignal - Auto-save to storage
  • JsonPersistence - JSON serialization
Neuron.to(DetailPage());        // Push
Neuron.off(HomePage());         // Replace
Neuron.back();                  // Pop
Neuron.toNamed('/settings');    // Named route

DevTools Integration

Built-in debugging support:

  • Signal state inspection
  • Event history tracking
  • Time-travel debugging

More Information

Classes

AggregateMiddleware<T>
Aggregate middleware - combine multiple middlewares.
AnimatedErrorMessage
AnimatedErrorMessage - Animated error message display.
AnimatedFormSlot<T>
AnimatedFormSlot - Reactive form field with built-in animations.
AnimatedSlot<T>
============================================================================ ADVANCED SLOT WIDGETS
AnimatedValueSlot<T extends num>
============================================================================ ADVANCED ANIMATION SLOTS
AsyncData<T>
Represents the data state of an async operation.
AsyncError<T>
Represents the error state of an async operation.
AsyncLoading<T>
Represents the loading state of an async operation.
AsyncSignal<T>
============================================================================ ASYNC SIGNAL<T> - ASYNC STATE MANAGEMENT
AsyncSlot<T>
A widget that rebuilds when an AsyncSignal changes.
AsyncState<T>
============================================================================ ASYNC STATE<T> - PURE DART ASYNC STATE REPRESENTATION
AuthGuard
BinaryPersistence<T>
Binary persistence for custom serialization.
ClampMiddleware
Clamp middleware - clamps numeric values to range.
CoalesceMiddleware<T>
Coalesce middleware - prevents null values.
CombinedSignal2<T1, T2, R>
============================================================================ COMBINED SIGNAL (COMBINE MULTIPLE SIGNALS)
CombinedSignal3<T1, T2, T3, R>
Combine 3 signals.
CombinedSignal4<T1, T2, T3, T4, R>
Combine 4 signals.
Computed<T>
A derived signal that automatically recalculates when dependencies change.
ComputedAsync<T>
============================================================================ COMPUTED ASYNC (DERIVED ASYNC SIGNALS)
ConditionalMiddleware<T>
Conditional middleware - only emit if condition is met.
ConditionalSlot<T>
ConditionalSlot - Shows widget based on condition, with optional fallback.
CounterSignal
============================================================================ COUNTER SIGNAL (NUMERIC HELPER)
DebouncedSignal<T>
============================================================================ RATE LIMITING SIGNALS
DebounceSlot<T>
DebounceSlot - Debounced rebuilds for performance.
DirectionalEffect
Direction-aware effect configuration for value changes.
Disposable
Interface for objects that need cleanup when no longer used.
DistinctSignal<T>
Distinct signal - filters out duplicate consecutive values.
EncryptedPersistence<T>
Encrypted persistence wrapper.
FormFieldWrapper<T>
FormFieldWrapper - Convenience wrapper for form fields with validation UI.
FormSignal<T>
Form field signal with validation support.
FormSlot<T>
Widget for binding FormSignal to UI.
FormValidationResult
Validation result for form fields.
FutureSignal<T>
============================================================================ FUTURE SIGNAL (FROM FUTURE)
GestureAnimatedSlot<T>
GestureAnimatedSlot - Combines gestures with animated state.
Hide
Hide widget when condition is true.
HistoryMiddleware<T>
History middleware - keeps track of previous values.
IconMorphSlot<T>
IconMorphSlot - Specialized morph for icon transitions.
IntervalSignal<T>
============================================================================ INTERVAL SIGNAL (PERIODIC UPDATES)
IsolateSignal<T, M>
============================================================================ ISOLATE SIGNAL (OFF-THREAD COMPUTATION)
JsonPersistence<T>
JSON persistence adapter.
LazySignal<T>
============================================================================ LAZY SIGNAL (LAZY INITIALIZATION)
LazySlot<T>
LazySlot - Lazy build widget until first value change.
ListSignal<E>
============================================================================ COLLECTION SIGNALS
LoggingMiddleware<T>
Logging middleware - logs value changes.
MapSignal<K, V>
Signal for Map with convenient mutation methods.
MemoizedSlot<T>
MemoizedSlot - Cache expensive builds with custom equality.
MemoryPersistence<T>
In-memory persistence (for testing).
MiddlewareSignal<T>
Signal with middleware support.
MorphableWidget
MorphableWidget - Configuration for a morphable state.
MorphConfig
============================================================================ MORPH SLOT - SHAPE/WIDGET MORPHING ANIMATIONS
MorphSlot<T>
MorphSlot - Widget morphing animations.
MultiSlot
============================================================================ MULTI SLOT - UNIFIED MULTI-SIGNAL WIDGET
Neuron
============================================================================
NeuronApp
============================================================================ 5. APP WRAPPER
NeuronAtom<T>
A modern, lightweight reactive value container.
NeuronAtomBuilder<T>
A widget that rebuilds when a NeuronAtom changes.
NeuronAtomPool
═══════════════════════════════════════════════════════════════════════════════ ATOM POOLING / ARENA ALLOCATION ═══════════════════════════════════════════════════════════════════════════════
NeuronBatch
═══════════════════════════════════════════════════════════════════════════════ BATCH SCOPE ═══════════════════════════════════════════════════════════════════════════════
NeuronController
============================================================================ 2. BASE CONTROLLER
NeuronFormState<T>
Form field state.
NeuronNavigationEntry
NeuronNavigationMiddleware
NeuronNavigationObserver
NeuronNavigator
NeuronNavigatorWidget
NeuronPerformanceMonitor
Performance monitoring for DevTools.
NeuronRoute
NeuronRouteContext
NeuronRouteGuard
NeuronRouteScope
NeuronRouteState
NeuronTransitions
NeuronTransitionSpec
PersistentSignal<T>
Signal with automatic persistence.
PulseSlot<T>
PulseSlot - Continuous pulsing animation for attention.
RateLimitMiddleware<T>
Rate limit middleware - limits how frequently values can be emitted.
RoleGuard
SanitizationMiddleware
String sanitization middleware.
SelectSlot<T, S>
Widget for using signal selectors inline.
SetSignal<E>
Signal for Set with convenient mutation methods.
ShapeConfig
Configuration for shape morphing.
ShapeMorphSlot<T>
ShapeMorphSlot - Morph between different shapes.
ShimmerSlot<T>
ShimmerSlot - Loading shimmer effect.
Show
Show widget when condition is true.
Signal<T>
============================================================================ SIGNAL<T> - CORE REACTIVE VALUE CONTAINER
SignalAction<T>
Action - Encapsulates async mutations with state tracking.
SignalMiddleware<T>
============================================================================ MIDDLEWARE AND INTERCEPTORS
SignalPersistence<T>
============================================================================ PERSISTENCE
SignalReaction<T>
============================================================================ EFFECTS AND REACTIONS
SignalSelector<T, S>
============================================================================ SIGNAL SELECTOR (GRANULAR REBUILDS)
SignalTransaction
Transaction - Batch multiple signal updates.
SignalUtils
============================================================================ UTILITIES
SimplePersistence<T>
Simple string persistence for primitive types.
Slot<T>
============================================================================ 4. SLOT WIDGETS (BINDING SIGNALS TO UI)
SlotEffect
════════════════════════════════════════════════════════════════════════════ SLOT EFFECTS & TRANSITIONS ════════════════════════════════════════════════════════════════════════════ Visual effects for slot animations.
SpringConfig
Spring physics configuration for natural motion.
SpringSlot<T extends num>
SpringSlot - Physics-based spring animations for natural motion.
StreamSignal<T>
============================================================================ STREAM SIGNAL (FROM STREAM)
ThrottledSignal<T>
Throttled signal - limits emission frequency.
ThrottleSlot<T>
ThrottleSlot - Throttled rebuilds for performance.
ToggleSignal
============================================================================ TOGGLE SIGNAL (BOOLEAN HELPER)
TransformMiddleware<T>
Transform middleware - transforms values.
TransitionSlot<T>
TransitionSlot - Animated transitions between different widgets.
UndoableSignal<T>
============================================================================ UNDOABLE SIGNAL (UNDO/REDO SUPPORT)
ValidationMiddleware<T>
Validation middleware - validates values.
ValidationResult
============================================================================ FORM SIGNAL WITH VALIDATION
Validators
Built-in validators.
VersionedPersistence<T>
Versioned persistence with migration support.
When
============================================================================ WHEN WIDGET (CONDITIONAL RENDERING)

Enums

FormAnimationEffect
Animation effect for form validation states.
FormFieldState
============================================================================ FORM SLOT - REACTIVE FORM HANDLING WITH ANIMATIONS
IconMorphStyle
Style options for icon morphing.
NeuronPageTransition
SlotTransition
Transition types for TransitionSlot.

Extension Types

AtomListener
A zero-cost abstraction for a listener handle.

Extensions

BooleanMorphExtensions on Signal<bool>
Extensions for boolean signals with common morph patterns.
FormSignalExtensions on Signal<T>
============================================================================ SIGNAL EXTENSIONS FOR FORM AND MORPH SLOTS
MorphSignalExtensions on Signal<T>
Extensions for morph-related signals.
NeuronControllerShorthand on NeuronController
Extension providing ultra-short signal factory methods on NeuronController.
NeuronControllerSignals on NeuronController
============================================================================ 3b. CONTROLLER SIGNAL FACTORY EXTENSIONS
NumericSignalSlotExtensions on Signal<T>
Extensions for numeric signals with interpolation.
SignalBatching on Signal
Extension to add batching support to signals.
SignalBinding on T
============================================================================ 3. SIGNAL BINDING EXTENSION
SignalExtensions on Signal<T>
Extension methods for signals.
SignalHelpers on Signal<T>
============================================================================ CONVENIENCE EXTENSIONS
SignalSlotExtensions on Signal<T>
============================================================================ COMPOSABLE SLOT MODIFIERS (Extension Methods)
SlotWidgetModifiers on Widget
Widget wrapper for chainable modifiers.

Properties

neuronErrorHandler ↔ void Function(String message, Object error, StackTrace? stackTrace)
Global error handler for Neuron framework errors.
getter/setter pair

Functions

batch(void updates()) → void
============================================================================ EFFECT HELPER ON CONTROLLER

Typedefs

MultiSlot2<T1, T2> = _LegacyMultiSlot2<T1, T2>
@Deprecated('Use MultiSlot.t2 instead')
MultiSlot3<T1, T2, T3> = _LegacyMultiSlot3<T1, T2, T3>
@Deprecated('Use MultiSlot.t3 instead')
MultiSlot4<T1, T2, T3, T4> = _LegacyMultiSlot4<T1, T2, T3, T4>
@Deprecated('Use MultiSlot.t4 instead')
MultiSlot5<T1, T2, T3, T4, T5> = _LegacyMultiSlot5<T1, T2, T3, T4, T5>
@Deprecated('Use MultiSlot.t5 instead')
NeuronRouteBuilder = Widget Function(BuildContext context, Map<String, dynamic> params)
Validator<T> = ValidationResult Function(T value)
Validator function type.

Exceptions / Errors

CircularDependencyError
============================================================================ COMPUTED<T> - DERIVED REACTIVE VALUES
TimeoutException
Exception for timeout operations.