### Basic Global Signal Setup in Flutter Source: https://dartsignals.dev/llms.txt Demonstrates setting up a global signal and using it within a Flutter widget. Ensure the signal is disposed of when no longer needed, though this example does not explicitly show disposal. ```dart import 'package:signals/signals_flutter.dart'; import 'package:flutter/material.dart'; final counter = signal(0); void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Signals with Global Signal'), ), body: Center( child: Watch((context) => Text('Value: $counter')), ), floatingActionButton: FloatingActionButton( onPressed: () => counter.value++, child: Icon(Icons.add), ), ), ); } } ``` -------------------------------- ### Initialize a Connector Source: https://dartsignals.dev/async/connect Start with a signal and use the `connect` method to create a connector. Streams will feed the signal's value. ```dart final s = signal(0); final c = connect(s); ``` -------------------------------- ### Implement EventSinkSignalMixin with a Custom Signal Source: https://dartsignals.dev/mixins/event-sink Example of creating a custom Signal that extends Signal> and mixes in EventSinkSignalMixin. This setup enables the signal to function as an EventSink. ```dart class MySignal extends Signal> with EventSinkSignalMixin { MySignal(int value) : super(AsyncState.data(value)); } ``` -------------------------------- ### Main Application Setup Source: https://dartsignals.dev/guides/persisted-signals Initializes the AppTheme and runs the MyApp widget. It's crucial to await theme initialization before runApp to ensure the theme is loaded correctly. ```dart void main() async{ final theme = AppTheme.instance; // We need to init before running the app to prevent the theme from flickering await theme.init(); runApp(MyApp()); } ``` -------------------------------- ### Custom Signal Implementation Source: https://dartsignals.dev/core/signal Provides an example of creating a custom signal by extending the `Signal` class. ```dart class MySignal extends Signal { MySignal(int value) : super(value); } ``` -------------------------------- ### Basic Signal Usage in Dart Source: https://dartsignals.dev/guides/value-notifier This example shows how to create and use signals, computed signals, and effects in a pure Dart environment. Ensure the 'signals' package is imported. ```dart import 'package:signals/signals.dart'; void main() { final count1 = signal(0); final count2 = signal(0); final total = computed(() => count1.value + count2.value); final isEven = computed(() => total.value.isEven); final isOdd = computed(() => total.value.isOdd); effect(() { print('$total even=$isEven odd=$isOdd'); }); } ``` -------------------------------- ### StreamSignalMixin Example Source: https://dartsignals.dev/llms.txt Shows how `StreamSignalMixin` allows a Signal to be used as a Stream. Listeners can be attached, and the signal's value can be updated, triggering stream events. ```dart class MySignal extends Signal with StreamSignalMixin { MySignal(super.internalValue); } void main() { final signal = MySignal(1); assert(signal is Signal); assert(signal is Stream); signal.listen((value) { print(value); }); signal.value = 2; } ``` -------------------------------- ### Settings Management with Signal Container and SharedPreferences Source: https://dartsignals.dev/llms.txt Example demonstrating how to use `signalContainer` with `SharedPreferences` for persistent settings. An `effect` is used to sync signal changes to `SharedPreferences`. ```dart class Settings { final SharedPreferences prefs; EffectCleanup? _cleanup; Settings(this.prefs) { _cleanup = effect(() { for (final entry in setting.store.entries) { final value = entry.value.peek(); if (prefs.getString(entry.key.$1) != value) { prefs.setString(entry.key.$1, value).ignore(); } } }); } late final setting = signalContainer( (val) => signal(prefs.getString(val.$1) ?? val.$2), cache: true, ); Signal get darkMode => setting(('dark-mode', 'false')); void dispose() { _cleanup?.call(); setting.dispose(); } } void main() { // Load or find instance late final SharedPreferences prefs = ...; // Create settings final settings = Settings(prefs); // Get value print('dark mode: ${settings.darkMode}'); // Update value settings.darkMode.value = 'true'; } ``` -------------------------------- ### Global Signal Example Source: https://dartsignals.dev/guides/dependency-injection Demonstrates using a global signal. This approach requires manual lifecycle management and disposal. It's suitable for select use cases like logging or analytics, not recommended for large applications. ```dart import 'package:signals/signals_flutter.dart'; import 'package:flutter/material.dart'; final counter = signal(0); void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Signals with Global Signal'), ), body: Center( child: Watch((context) => Text('Value: $counter')), ), floatingActionButton: FloatingActionButton( onPressed: () => counter.value++, child: Icon(Icons.add), ), ), ); } } ``` -------------------------------- ### Define and Use MySignal with QueueSignalMixin Source: https://dartsignals.dev/mixins/queue Example of defining a custom Signal that extends Signal> and mixes in QueueSignalMixin>. Demonstrates initializing the signal with a queue, setting up an effect to observe its length, and adding elements to the queue. ```dart class MySignal extends Signal> with QueueSignalMixin> { MySignal(super.internalValue); } void main() { final q = Queue(); q.addFirst(1); final signal = MySignal(q); effect(() { print(signal.length); }); signal.addLast(4); } ``` -------------------------------- ### SinkSignalMixin Example Source: https://dartsignals.dev/llms.txt Demonstrates using `SinkSignalMixin` to treat a Signal as a Sink. The `add` method updates the signal's value, and `close` disposes of it. ```dart class MySignal extends Signal with SinkSignalMixin { MySignal(super.internalValue); } void main() { final signal = MySignal(0); signal.add(1); print(signal.value); // 1 signal.close(); print(signal.disposed); // true } ``` -------------------------------- ### Example Usage of Signals in HookWidget Source: https://dartsignals.dev/flutter/hooks Demonstrates the basic usage of `useSignal`, `useComputed`, and `useSignalEffect` within a `HookWidget`. All created signals and effects are automatically cleaned up when the widget is unmounted. ```dart import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:signals_hooks/signals_hooks.dart'; class Example extends HookWidget { const Example({super.key}); @override Widget build(BuildContext context) { final count = useSignal(0); final doubleCount = useComputed(() => count.value * 2); useSignalEffect(() { debugPrint('count: $count, double: $doubleCount'); }); return Scaffold( body: Center( child: Text('Count: $count'), ), floatingActionButton: FloatingActionButton( onPressed: () => count.value++, child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### SignalProvider Example Source: https://dartsignals.dev/flutter/signal-provider Demonstrates how to use SignalProvider to create and access a Counter signal within a Flutter widget tree. The signal is created with an initial value and can be incremented via a FloatingActionButton. ```dart import 'package:signals/signals_flutter.dart'; import 'package:flutter/material.dart'; class Counter extends FlutterSignal { Counter([super.value = 0]); void increment() => value++; } class Example extends StatelessWidget { const Example({super.key}); @override Widget build(BuildContext context) { return SignalProvider( create: () => Counter(0), child: Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('Counter'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'You have pushed the button this many times:', ), Builder(builder: (context) { final counter = SignalProvider.of(context); return Text( '$counter', style: Theme.of(context).textTheme.headlineMedium, ); }), ], ), ), floatingActionButton: Builder(builder: (context) { final counter = SignalProvider.of(context, listen: false)!; return FloatingActionButton( onPressed: counter.increment, tooltip: 'Increment', child: const Icon(Icons.add), ); }), ), ); } } ``` -------------------------------- ### Create Basic FlutterSignal Source: https://dartsignals.dev/flutter/signal Use `signals_flutter` to create signals that extend `ValueNotifier`. This example demonstrates creating a basic integer signal and asserting its types. ```dart import 'package:signals/signals_flutter.dart'; final count = signal(0); assert(count is Signal); assert(count is FlutterSignal); assert(count is FlutterReadonlySignal); assert(count is ValueNotifier); ``` -------------------------------- ### ValueNotifier with Manual Listeners Source: https://dartsignals.dev/guides/value-notifier Demonstrates managing derived state (total, isEven, isOdd) using ValueNotifier and manual listeners. Requires explicit listener setup and disposal. ```dart class MyWidget extends ... { final count1 = ValueNotifier(0); final count2 = ValueNotifier(0); // React to count 1 changing count1.addListener(() { if (mounted) setState(() {}); }); // React to count 2 changing count2.addListener(() { if (mounted) setState(() {}); }); int get total => count1.value + count2.value; int get isEven => total.isEven; int get isOdd => total.isOdd; @override void dispose() { super.dispose(); count1.dispose(); count2.dispose(); } @override Widget build(BuildContext context) { // If using setState return Text('$total even=$isEven odd=$isOdd'); // Or if you are using with ValueListenableBuilder return ValueListenableBuilder( valueListenable: count1, builder: (context, count1Val, child) { // React when count 1 changes return ValueListenableBuilder( valueListenable: count2, builder: (context, count2Val, child) { // React when count 2 changes return Text('$total even=$isEven odd=$isOdd'); }, ); }, ); } } ``` -------------------------------- ### Initialize LoggingSignalsObserver Source: https://dartsignals.dev/utilities/observer Set the SignalsObserver.instance to LoggingSignalsObserver at the start of your application to log all signal updates to the console. This is recommended for debug or profile modes due to a slight performance impact. ```dart void main() { SignalsObserver.instance = LoggingSignalsObserver(); // or custom observer ... } ``` -------------------------------- ### Test useSignal Hook Source: https://dartsignals.dev/flutter/hooks Example of testing `useSignal` with `flutter_test` and `HookBuilder`. This demonstrates how to interact with and assert the state of a signal during widget tests. ```dart import 'package:flutter/widgets.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:signals_hooks/signals_hooks.dart'; void main() { testWidgets('useSignal', (tester) async { late Signal state; await tester.pumpWidget( HookBuilder(builder: (context) { state = useSignal(42); return GestureDetector( onTap: () => state.value++, child: Text('$state', textDirection: TextDirection.ltr), ); }), ); expect(state.value, 42); expect(find.text('42'), findsOneWidget); // Click text and wait await tester.tap(find.text('42')); await tester.pumpAndSettle(); expect(state.value, 43); expect(find.text('43'), findsOneWidget); }); } ``` -------------------------------- ### TrackedSignalMixin Example Source: https://dartsignals.dev/llms.txt TrackedSignalMixin stores the initial and previous values of a signal. Ensure values are immutable or copied when changed to prevent initial and previous values from being the same. ```dart class MySignal extends Signal with TrackedSignalMixin { MySignal(super.internalValue); } void main() { final signal = MySignal(0); signal.value = 1; print(signal.initialValue); // 0 print(signal.previousValue); // null signal.value = 2; print(signal.initialValue); // 0 print(signal.previousValue); // 1 } ``` -------------------------------- ### Implement ValueListenableSignalMixin in Dart Source: https://dartsignals.dev/llms.txt This example shows how to create a custom Signal that also implements ValueListenable, allowing it to be used with Flutter's ValueListenable widgets. ```dart class MySignal extends Signal with ValueListenableSignalMixin { MySignal(super.internalValue); } void main() { final signal = MySignal(0); assert(signal is ReadonlySignal); assert(signal is ValueListenable); final listener = () => print(signal.value); signal.addListener(listener); signal.value = 1; signal.removeListener(listener); signal.value = 2; } ``` -------------------------------- ### Using Signals with ValueNotifier API Source: https://dartsignals.dev/flutter/value-notifier You can replace any ValueNotifier with a Signal and implement both APIs. This example demonstrates using the ValueNotifier API with a Signal. ```dart import 'package:flutter/foundation.dart'; import 'package:signals/signals_flutter.dart'; final count = ValueNotifier(0); final count = signal(0); count.addListener(() => print(count.value)); count.value = 1; print(count.value); count.notifyListeners(); count.dispose(); ``` -------------------------------- ### Lite Ref Scoped Signal Example Source: https://dartsignals.dev/guides/dependency-injection Demonstrates using a scoped Ref for a disposable signal. The signal is automatically disposed when the widget is removed. Requires `Ref.scoped` and `LiteRefScope`. ```dart final counterRef = Ref.scoped( (_) => signal(0), dispose: (instance) => instance.dispose(), ); void main() { runApp(LiteRefScope(child: MyApp())); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final counter = counterRef.of(context); return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Signals with Zones'), ), body: Center( child: Watch((context) => Text('Value: $counter')), ), floatingActionButton: FloatingActionButton( onPressed: () => counter.value++, child: Icon(Icons.add), ), ), ); } } ``` -------------------------------- ### Flutter Hooks Example with Signals Source: https://dartsignals.dev/llms.txt Integrates signals with flutter_hooks for reactive UI. Automatically cleans up signals and effects when the widget unmounts. Requires importing `flutter/material.dart`, `flutter_hooks/flutter_hooks.dart`, and `signals_hooks/signals_hooks.dart`. ```dart import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:signals_hooks/signals_hooks.dart'; class Example extends HookWidget { const Example({super.key}); @override Widget build(BuildContext context) { final count = useSignal(0); final doubleCount = useComputed(() => count.value * 2); useSignalEffect(() { debugPrint('count: $count, double: $doubleCount'); }); return Scaffold( body: Center( child: Text('Count: $count'), ), floatingActionButton: FloatingActionButton( onPressed: () => count.value++, child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### Signals.dart Minimal Updates Example 2 Source: https://dartsignals.dev/llms.txt Illustrates how computed signals cache their values and only recompute when dependencies change. Updates propagate efficiently through a chain of computed signals. ```dart import 'package:signals/signals.dart'; final a = signal(0); final b = signal(0); final c = computed(() => a.value + b.value); final d = computed(() => c.value + 1); final e = computed(() => d.value + 1); // All the callbacks will be called print(e.value); // 2 // None of the callbacks will be called because the // value is cached at each node print(e.value); // 2 // Only the callbacks that need to be updated // will be called b.value = 1; print(e.value); // 3 ``` -------------------------------- ### Using ListSignalMixin with a Custom Signal Source: https://dartsignals.dev/mixins/list Demonstrates how to create a custom Signal type that incorporates ListSignalMixin for reactive list operations. This example shows adding, removing, and checking for elements within the signal. ```dart class MySignal extends Signal> with IterableSignalMixin>, ListSignalMixin> { MySignal(super.internalValue); } void main() { final signal = MySignal([1, 2, 3]); effect(() { print(signal.length); }); signal.add(4); signal.remove(1); print(signal.contains(2)); // true } ``` -------------------------------- ### Persisting Signal Values Offline in Flutter Source: https://dartsignals.dev/llms.txt This example shows how to use Signals to manage application theme and persist changes offline. Ensure signals are initialized before running the app to prevent flickering. ```dart class AppTheme { final sourceColor = ColorSignal( Colors.blue, 'sourceColor', ); final themeMode = EnumSignal( ThemeMode.system, 'themeMode', ThemeMode.values, ); static AppTheme instance = AppTheme(); Future init() async { await Future.wait([ sourceColor.init(), themeMode.init(), ]); } } void main() async{ final theme = AppTheme.instance; // We need to init before running the app to prevent the theme from flickering await theme.init(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final theme = AppTheme.instance; return MaterialApp( theme: ThemeData.light().copyWith( colorScheme: ColorScheme.fromSeed( seedColor: theme.sourceColor.watch(context), brightness: Brightness.light, ), ), darkTheme: ThemeData.dark().copyWith( colorScheme: ColorScheme.fromSeed( seedColor: theme.sourceColor.watch(context), brightness: Brightness.dark, ), ), themeMode: theme.themeMode.watch(context), home: Scaffold( appBar: AppBar( title: Text('Persisted Signals'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () { theme.sourceColor.value = Colors.red; }, child: Text('Change Color'), ), ElevatedButton( onPressed: () { theme.themeMode.value = ThemeMode.dark; }, child: Text('Change Theme'), ), ], ), ), ), ); } } ``` -------------------------------- ### Custom Signal with ValueNotifier and Stream Mixins Source: https://dartsignals.dev/guides/value-notifier This example demonstrates creating a custom signal that extends Signal, ValueNotifier, and Stream. It requires importing 'signals_flutter.dart'. The custom signal can be listened to as a stream and subscribed to in effects. ```dart import 'package:signals/signals_flutter.dart'; class CustomSignal extends Signal with ValueNotifierSignalMixin, SinkSignalMixin, StreamSignalMixin { CustomSignal(T value) : super(value); } class Counter extends CustomSignal { Counter(int value) : super(value); } void main() { final counter = Counter(0); assert(counter is Signal); assert(counter is ValueNotifier); assert(counter is Stream); // Listen to the stream counter.listen((value) { print('stream: $value'); }); // Subscribe in an effect effect(() { print('effect: $counter'); }); counter.add(1); print(counter.value); // 1 counter.value = 2; print(counter.value); // 2 counter.close(); print(counter.disposed); // true } ``` -------------------------------- ### Signals.dart Minimal Updates Example 1 Source: https://dartsignals.dev/llms.txt Demonstrates how unread computed signals are not computed, saving computation. If the final computed value is never read, none of the intermediate computations are performed. ```dart import 'package:signals/signals.dart'; final a = signal(0); final b = computed(() => a.value + 1); final c = computed(() => b.value + 1); final d = computed(() => c.value + 1); // if you never read `d` then none of the callbacks will be called // All the callbacks will be called print(d.value); // 3 // None of the callbacks will be called because the // value is cached at each node print(d.value); // 3 ``` -------------------------------- ### Download Documentation for Firebase Studio Source: https://dartsignals.dev/reference/ai Download the documentation file locally to use as context in Firebase Studio. ```bash curl https://dartsignals.dev/llms.txt > signals.md ``` -------------------------------- ### Get Signal Value with useSignalValue Hook Source: https://dartsignals.dev/llms.txt Gets the value of a signal directly within a HookWidget. The widget rebuilds automatically when the signal's value changes. Requires importing `flutter_hooks/flutter_hooks.dart` and `signals_hooks/signals_hooks.dart`. ```dart import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:signals_hooks/signals_hooks.dart'; class Example extends HookWidget { final Signal count; const Example(this.count, {super.key}); @override Widget build(BuildContext context) { final counter = useSignalValue(count); return Text('Count: $counter'); } } ``` -------------------------------- ### Get the value of a signal directly in a HookWidget Source: https://dartsignals.dev/flutter/hooks Use `useSignalValue` to get the current value of a `Signal` directly within a `HookWidget`. Note that this hook does not cause the widget to rebuild when the signal changes; use `useSignal` or `useExistingSignal` for reactive updates. ```dart class Example extends HookWidget { final Signal count; const Example(this.count, {super.key}); @override Widget build(BuildContext context) { final counter = useSignalValue(count); return Text('Count: $counter'); } } ``` -------------------------------- ### Query Documentation with Gemini CLI Source: https://dartsignals.dev/reference/ai Use the Gemini CLI to query the documentation by creating a GEMINI.md file with the documentation URL. ```bash https://dartsignals.dev/llms.txt ``` ```bash gemini "How do I use signals?" ``` -------------------------------- ### Get AsyncSignal Stack Trace Source: https://dartsignals.dev/async/state The .stackTrace getter returns the stack trace associated with the error in the AsyncSignal, if an error exists. ```dart final s = asyncSignal(AsyncState.error('error', StackTrace(...))); print(s.stackTrace); // StackTrace(...) or null ``` -------------------------------- ### Incorrect Effect Creation with SignalsMixin Source: https://dartsignals.dev/mixins/signals-mixin Effects should not be declared as late final fields because they will not be evaluated. This example demonstrates an incorrect approach. ```dart class _MyState extends State with SignalsMixin { late final effect = createEffect(() => print('Effect created')); } ``` -------------------------------- ### Bi-directional Signal Dependency (Potential Loop) Source: https://dartsignals.dev/guides/bi-directional-data-flow This example demonstrates two signals dependent on each other, which can lead to an `EffectCycleDetectionError` if not handled properly. ```dart final a = signal(0); final b = signal(0); effect(() { b.value = a.value + 1; }); effect(() { a.value = b.value + 1; }); ``` -------------------------------- ### Using Signals with GetIt in Flutter Source: https://dartsignals.dev/llms.txt Demonstrates integrating Signals with GetIt for service location. Register the signal as a singleton with GetIt before running the application. ```dart import 'package:signals/signals_flutter.dart'; import 'package:get_it/get_it.dart'; import 'package:flutter/material.dart'; void main() { GetIt.I.registerSingleton>(signal(0)); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final counter = GetIt.I.get>(); return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Signals with GetIt'), ), body: Center( child: Watch((context) => Text('Value: $signal')), ), floatingActionButton: FloatingActionButton( onPressed: () => counter.value++, child: Icon(Icons.add), ), ), ); } } ``` -------------------------------- ### AsyncState Mapping Methods Source: https://dartsignals.dev/async/state Demonstrates how to use .map and .maybeMap to handle different states of an AsyncSignal. ```APIDOC ## AsyncState Mapping Methods ### Description These methods provide convenient ways to handle the different states (`data`, `error`, `loading`) of an `AsyncSignal`. ### Method `.map()` and `.maybeMap()` ### Endpoint N/A (Client-side Dart code) ### Parameters N/A ### Request Body N/A ### Examples #### .map Enforces handling of all possible states. ```dart final signal = asyncSignal(AsyncState.data(1)); final result = signal.value.map( data: (value) => 'Value: $value', error: (error, stackTrace) => 'Error: $error', loading: () => 'Loading...', ); print(result); // 'Value: 1' ``` #### .maybeMap Provides a default case and optional overrides for specific states. ```dart final signal = asyncSignal(AsyncState.data(1)); final result = signal.value.maybeMap( data: (value) => 'Value: $value', orElse: () => 'Loading...', // Default case ); print(result); // 'Value: 1' ``` ``` -------------------------------- ### Get Current AsyncSignal Error Source: https://dartsignals.dev/async/state The .error getter returns the current error of the AsyncSignal if one exists, otherwise it returns null. ```dart final s = asyncSignal(AsyncState.error('error', null)); print(s.error); // 'error' or null ``` -------------------------------- ### Get Current AsyncSignal Value Source: https://dartsignals.dev/async/state The .value getter returns the current value of the AsyncSignal if one exists, otherwise it returns null. ```dart final s = asyncSignal(AsyncState.data(1)); print(s.value); // 1 or null ``` -------------------------------- ### AsyncSignal Initialization and State Updates Source: https://dartsignals.dev/async/state Demonstrates how to initialize an AsyncSignal with an initial AsyncState and how to update its value to loading or error states. ```APIDOC ## AsyncSignal Initialization and State Updates ### Description This section shows how to create an `AsyncSignal` and transition it through different states like loading and error. ### Method `asyncSignal()` constructor and direct value assignment. ### Endpoint N/A (Client-side Dart code) ### Request Body N/A ### Request Example ```dart final s = asyncSignal(AsyncState.data(1)); s.value = AsyncState.loading(); // or AsyncLoading(); s.value = AsyncState.error('Error', null); // or AsyncError(); ``` ### Response N/A ``` -------------------------------- ### Register Signal with GetIt Source: https://dartsignals.dev/guides/dependency-injection Uses GetIt, a simple service locator, to manage a Signal instance. Register the signal as a singleton with GetIt before running the application. ```dart import 'package:signals/signals_flutter.dart'; import 'package:get_it/get_it.dart'; import 'package:flutter/material.dart'; void main() { GetIt.I.registerSingleton>(signal(0)); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final counter = GetIt.I.get>(); return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Signals with GetIt'), ), body: Center( child: Watch((context) => Text('Value: $signal')), ), floatingActionButton: FloatingActionButton( onPressed: () => counter.value++, child: Icon(Icons.add), ), ), ); } } ``` -------------------------------- ### Create and Use a Signal Source: https://dartsignals.dev/core/signal Creates a new signal with an initial value and demonstrates reading and writing to it. Ensure the 'signals' package is imported. ```dart import 'package:signals/signals.dart'; final counter = signal(0); // Read value from signal, logs: 0 print(counter.value); // Write to a signal counter.value = 1; ``` -------------------------------- ### Initialize AsyncSignal with AsyncState Source: https://dartsignals.dev/async/state Demonstrates initializing an AsyncSignal with an initial AsyncState.data value and how to update it to loading or error states. ```dart final s = asyncSignal(AsyncState.data(1)); s.value = AsyncState.loading(); // or AsyncLoading(); s.value = AsyncState.error('Error', null); // or AsyncError(); ``` -------------------------------- ### Get Current AsyncState StackTrace Source: https://dartsignals.dev/llms.txt The .stackTrace property returns the stack trace associated with the current error if it exists, otherwise it returns null. ```dart final s = asyncSignal(AsyncState.error('error', StackTrace.current)); print(s.stackTrace); // StackTrace(...) or null ``` -------------------------------- ### Initialize a Signal Connector Source: https://dartsignals.dev/llms.txt Initialize a signal connector using the `connect` method, which takes an existing signal as an argument. This sets up a mechanism to feed streams into the signal. ```dart final s = signal(0); final c = connect(s); ``` -------------------------------- ### Create In-Memory KeyValueStore Source: https://dartsignals.dev/guides/persisted-signals An in-memory implementation of KeyValueStore for testing purposes. Data is lost when the app closes. ```dart class InMemoryStore implements KeyValueStore { final Map _store = {}; @override Future getItem(String key) async { return _store[key]; } @override Future removeItem(String key) async { _store.remove(key); } @override Future setItem(String key, String value) async { _store[key] = value; } } ``` -------------------------------- ### Provide Documentation Context with Claude Code Source: https://dartsignals.dev/reference/ai Add the documentation to your context for Claude Code by providing the documentation URL. ```bash claude --context https://dartsignals.dev/llms.txt ``` -------------------------------- ### StreamBuilder with Counter Signal Source: https://dartsignals.dev/llms.txt Use StreamBuilder to build a widget that updates automatically when a signal emits a new value. This example demonstrates a counter that increments and updates the UI. ```dart import 'package:flutter/material.dart'; import 'package:signals/signals_flutter.dart'; class Counter extends Signal with StreamSignalMixin { Counter(int value) : super(value); } void main() { final counter = Counter(0); runApp( MaterialApp( home: Scaffold( appBar: AppBar( title: Text('StreamSignalMixin Example'), ), body: Center( child: StreamBuilder( stream: counter, builder: (context, snapshot) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('You have pushed the button this many times:'), Text( '${snapshot.data}', style: Theme.of(context).textTheme.headline4, ), ], ); }, ), ), floatingActionButton: FloatingActionButton( onPressed: () => counter.value++, tooltip: 'Increment', child: Icon(Icons.add), ), ), ), ); } ``` -------------------------------- ### Create a MapSignal Source: https://dartsignals.dev/flutter/hooks Use `useMapSignal` to create a new `MapSignal` and subscribe to its changes. Suitable for managing key-value data structures. ```dart class MyWidget extends HookWidget { @override Widget build(BuildContext context) { final map = useMapSignal({'a': 1, 'b': 2}); return Text('${map.value}'); } } ``` -------------------------------- ### ChangeNotifier for Derived State Source: https://dartsignals.dev/guides/value-notifier An example of using ChangeNotifier to manage derived state. This approach centralizes state logic but still recalculates all derived values on every update. ```dart class Counter extends ChangeNotifier { int _count1 = 0; int get count1 => _count1; set count1(int value) { _count1 = value; notifyListeners(); } int _count2 = 0; int get count2 => _count2; set count2(int value) { _count2 = value; notifyListeners(); } int get total => count1 + count2; int get isEven => total.isEven; int get isOdd => total.isOdd; } ``` -------------------------------- ### ValueNotifier vs. Signals Initialization Source: https://dartsignals.dev/guides/value-notifier Compares the initialization syntax for ValueNotifier and Signals. Signals offer a more concise way to declare reactive state. ```dart // Value Notifier final count = ValueNotifier(0); // Signals final count = signal(0); ``` -------------------------------- ### MyApp Widget with Theme Integration Source: https://dartsignals.dev/guides/persisted-signals Builds the MaterialApp, integrating the theme managed by AppTheme. Signals are watched within the build method to react to changes. Persisted changes will be reflected here. ```dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final theme = AppTheme.instance; return MaterialApp( theme: ThemeData.light().copyWith( colorScheme: ColorScheme.fromSeed( seedColor: theme.sourceColor.watch(context), brightness: Brightness.light, ), ), darkTheme: ThemeData.dark().copyWith( colorScheme: ColorScheme.fromSeed( seedColor: theme.sourceColor.watch(context), brightness: Brightness.dark, ), ), themeMode: theme.themeMode.watch(context), home: Scaffold( appBar: AppBar( title: Text('Persisted Signals'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () { theme.sourceColor.value = Colors.red; }, child: Text('Change Color'), ), ElevatedButton( onPressed: () { theme.themeMode.value = ThemeMode.dark; }, child: Text('Change Theme'), ), ], ), ), ), ); } } ``` -------------------------------- ### Create a SetSignal Source: https://dartsignals.dev/flutter/hooks Use `useSetSignal` to create a new `SetSignal` and subscribe to its changes. Ideal for managing unique collections. ```dart class MyWidget extends HookWidget { @override Widget build(BuildContext context) { final set = useSetSignal({1, 2, 3}); return Text('${set.value}'); } } ``` -------------------------------- ### Basic ChangeStackSignal Usage Source: https://dartsignals.dev/value/change-stack Demonstrates the fundamental usage of ChangeStackSignal, including setting values, printing the current value, and performing undo/redo operations. ```dart final s = ChangeStackSignal(0, limit: 5); s.value = 1; s.value = 2; s.value = 3; print(s.value); // 3 s.undo(); print(s.value); // 2 s.redo(); print(s.value); // 3 ``` -------------------------------- ### Implement SharedPreferencesStore Source: https://dartsignals.dev/llms.txt Concrete implementation of KeyValueStore using SharedPreferences for persisting data. It handles lazy initialization of SharedPreferences. ```dart class SharedPreferencesStore implements KeyValueStore { SharedPreferencesStore(); SharedPreferences? prefs; Future init() async { prefs ??= await SharedPreferences.getInstance(); return prefs!; } @override Future getItem(String key) async { final prefs = await init(); return prefs.getString(key); } @override Future removeItem(String key) async { final prefs = await init(); prefs.remove(key); } @override Future setItem(String key, String value) async { final prefs = await init(); prefs.setString(key, value); } } ``` -------------------------------- ### Test useSignal Hook with Flutter Hooks Source: https://dartsignals.dev/llms.txt Use flutter_test and HookBuilder to test hooks that utilize signals. This example verifies the state update and UI re-rendering after a signal change. ```dart import 'package:flutter/widgets.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:signals_hooks/signals_hooks.dart'; void main() { testWidgets('useSignal', (tester) async { late Signal state; await tester.pumpWidget( HookBuilder(builder: (context) { state = useSignal(42); return GestureDetector( onTap: () => state.value++, child: Text('$state', textDirection: TextDirection.ltr), ); }), ); expect(state.value, 42); expect(find.text('42'), findsOneWidget); // Click text and wait await tester.tap(find.text('42')); await tester.pumpAndSettle(); expect(state.value, 43); expect(find.text('43'), findsOneWidget); }); } ``` -------------------------------- ### LLM Documentation Endpoint Source: https://dartsignals.dev/reference/ai This URL provides all documentation pages concatenated into a single Markdown file, suitable for LLM consumption. ```text https://dartsignals.dev/llms.txt ``` -------------------------------- ### Create SharedPreferences KeyValueStore Source: https://dartsignals.dev/guides/persisted-signals Implementation of KeyValueStore using Flutter's SharedPreferences. Initializes SharedPreferences lazily. ```dart class SharedPreferencesStore implements KeyValueStore { SharedPreferencesStore(); SharedPreferences? prefs; Future init() async { prefs ??= await SharedPreferences.getInstance(); return prefs!; } @override Future getItem(String key) async { final prefs = await init(); return prefs.getString(key); } @override Future removeItem(String key) async { final prefs = await init(); prefs.remove(key); } @override Future setItem(String key, String value) async { final prefs = await init(); prefs.setString(key, value); } } ``` -------------------------------- ### ValueNotifierSignalMixin Example Source: https://dartsignals.dev/llms.txt ValueNotifierSignalMixin implements ValueNotifier for a Readonly Signal, allowing it to be used with Flutter widgets that expect a ValueNotifier. Listeners are subscribed to signal dependencies by default; use untracked to prevent this. ```dart class MySignal extends Signal with ValueNotifierSignalMixin { MySignal(super.internalValue); } void main() { final signal = MySignal(0); assert(signal is ReadonlySignal); assert(signal is ValueNotifier); final listener = () => print(signal.value); signal.addListener(listener); signal.value = 1; signal.removeListener(listener); signal.value = 2; } ``` ```dart final signal = MySignal(0); final dep = signal(0); final listener = () { untracked(() { print(signal.value); print(dep.value); }); }; signal.addListener(listener); ``` -------------------------------- ### Implement InMemoryStore for Testing Source: https://dartsignals.dev/llms.txt An in-memory implementation of KeyValueStore for testing purposes. It stores data in a map and does not persist across app restarts. ```dart class InMemoryStore implements KeyValueStore { final Map _store = {}; @override Future getItem(String key) async { return _store[key]; } @override Future removeItem(String key) async { _store.remove(key); } @override Future setItem(String key, String value) async { _store[key] = value; } } ``` -------------------------------- ### Use ValueListenableBuilder with Signals in Flutter Source: https://dartsignals.dev/llms.txt This example demonstrates how to use Flutter's `ValueListenableBuilder` widget to display the current value of a Signal, automatically rebuilding the widget when the Signal's value changes. ```dart import 'package:flutter/material.dart'; import 'package:signals/signals_flutter.dart'; final counter = signal(0); class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return ValueListenableBuilder( valueListenable: counter, builder: (context, value, child) { return Text('Count: $value'); }, ); } } ``` -------------------------------- ### Using TrackedSignalMixin in Dart Source: https://dartsignals.dev/mixins/tracked Demonstrates how to use TrackedSignalMixin to create a signal that tracks its initial and previous values. The initial value is set when the signal is created, and the previous value is updated each time the signal's value is changed. ```dart class MySignal extends Signal with TrackedSignalMixin { MySignal(super.internalValue); } void main() { final signal = MySignal(0); signal.value = 1; print(signal.initialValue); // 0 print(signal.previousValue); // null signal.value = 2; print(signal.initialValue); // 0 print(signal.previousValue); // 1 } ``` -------------------------------- ### AppTheme Class with Signals Source: https://dartsignals.dev/guides/persisted-signals Defines an AppTheme class using ColorSignal and EnumSignal for managing theme properties. Ensure signals are initialized before use to prevent flickering. ```dart class AppTheme { final sourceColor = ColorSignal( Colors.blue, 'sourceColor', ); final themeMode = EnumSignal( ThemeMode.system, 'themeMode', ThemeMode.values, ); static AppTheme instance = AppTheme(); Future init() async { await Future.wait([ sourceColor.init(), themeMode.init(), ]); } } ``` -------------------------------- ### Isolating Rebuilds with Builder and .watch(context) Source: https://dartsignals.dev/flutter/watch Demonstrates how to use `Builder` with the `.watch(context)` extension to isolate rebuilds. The outer `Text` widget remains static while the inner one updates. ```dart final signal = signal(10); ... @override Widget build(BuildContext context) { // Called once return Column( children: [ Builder( builder: (context) { // Called every time the signal changes final count = signal.watch(context); return Text('$count'); }, ), Text('Not rebuilt'), ], ); } ``` -------------------------------- ### .limit Source: https://dartsignals.dev/value/change-stack There is an optional limit that can be set for explicit stack size. ```APIDOC ## .limit ### Description There is an optional limit that can be set for explicit stack size. ### Method N/A (Property access or initialization parameter) ### Endpoint N/A (Instance property or constructor parameter) ### Parameters None (when accessing, it returns the limit) ### Request Example ```dart final s = ChangeStackSignal(0, limit: 2); s.value = 1; s.value = 2; s.value = 3; print(s.value); // 3 s.undo(); s.undo(); print(s.value); // 1 print(s.canUndo); // false s.redo(); print(s.value); // 2 ``` ### Response #### Success Response (integer) - **value** (integer) - The maximum size of the undo/redo stack. ``` -------------------------------- ### Create a ListSignal Source: https://dartsignals.dev/flutter/hooks Use `useListSignal` to create a new `ListSignal` and subscribe to its changes. This is useful for managing observable lists. ```dart class MyWidget extends HookWidget { @override Widget build(BuildContext context) { final list = useListSignal([1, 2, 3]); return Text('${list.value}'); } } ``` -------------------------------- ### Create an AsyncSignal with an initial state Source: https://dartsignals.dev/flutter/hooks Use `useAsyncSignal` to create a new `AsyncSignal` initialized with a specific `AsyncState`, such as `AsyncState.loading()`. The widget can then reactively display content based on the signal's state. ```dart class MyWidget extends HookWidget { @override Widget build(BuildContext context) { final signal = useAsyncSignal(AsyncState.loading()); return signal.value.map( data: (value) => Text('$value'), error: (error, stack) => Text('$error'), loading: () => const CircularProgressIndicator(), ); } } ``` -------------------------------- ### Flutter Widget with Signals and Watch Source: https://dartsignals.dev/guides/value-notifier Illustrates the equivalent Flutter widget using Signals, showcasing reduced boilerplate for state management and reactivity. It utilizes `watch` for automatic dependency tracking. ```dart import 'package:signals/signals_flutter.dart'; class MyWidget extends ... { final count1 = signal(0); final count2 = signal(0); @override Widget build(BuildContext context) { // If using setState return Text('${count1.watch(context)} - ${count2.watch(context)}'); // Or if you are using with Watch return Watch((context) => Text('$count1 - $count2')); } } ``` -------------------------------- ### Using SinkSignalMixin with a Custom Signal Source: https://dartsignals.dev/mixins/sink Demonstrates how to create a custom Signal that extends Signal and mixes in SinkSignalMixin. The .add() method updates the signal's value, and .close() disposes of it. ```dart class MySignal extends Signal with SinkSignalMixin { MySignal(super.internalValue); } void main() { final signal = MySignal(0); signal.add(1); print(signal.value); // 1 signal.close(); print(signal.disposed); // true } ``` -------------------------------- ### .canRedo Source: https://dartsignals.dev/value/change-stack Returns true if there are changes in the redo stack and can move forward. ```APIDOC ## .canRedo ### Description Returns true if there are changes in the redo stack and can move forward. ### Method N/A (Property access on an instance) ### Endpoint N/A (Instance property) ### Parameters None ### Response #### Success Response (boolean) - **value** (boolean) - True if redo is possible, false otherwise. ### Response Example ```dart // Assuming 's' is an instance of ChangeStackSignal if (s.canRedo) { print('Can redo'); } else { print('Cannot redo'); } ``` ``` -------------------------------- ### ChangeStackSignal with Undo/Redo Source: https://dartsignals.dev/llms.txt Demonstrates `ChangeStackSignal` for tracking signal values over time, allowing undo and redo operations. The `limit` parameter controls the stack size. ```dart final s = ChangeStackSignal(0, limit: 5); s.value = 1; s.value = 2; s.value = 3; print(s.value); // 3 s.undo(); print(s.value); // 2 s.redo(); print(s.value); // 3 ```