सार्वजनिक जानकारी से बना चयन मार्गदर्शन। केवल संदर्भ हेतु।
StateBeacon एक हल्का, प्रतिक्रियाशील अवस्था प्रबंधन समाधान है जो Dart और Flutter के लिए है और एप्लिकेशन अवस्था को प्रबंधित करने के लिए सरल मूलभूत तत्व प्रदान करता है। इसका जोर प्रतिक्रियाशीलता और उपयोग में आसानी पर है, जिससे डेवलपर्स को न्यूनतम बॉलरप्लेट के साथ प्रतिक्रियाशील UI बनाने में सक्षम बनाता है। प्रदर्शन और सरलता के लिए बनाया गया, यह विभिन्न प्लेटफॉर्मों पर Flutter प्रोजेक्ट में बिना किसी दिक्कत के एकीकृत हो सकता है। पैकेज बहुत छोटे स्तर पर अपडेट और कुशल पुनर्निर्माण का समर्थन करता है, जिससे यह जटिलता के बिना डायनामिक अवस्था परिवर्तन की आवश्यकता वाले ऐप्स के लिए आदर्श है। इसका डिज़ाइन स्पष्ट, बनाए रखने योग्य कोड को बढ़ावा देता है उपयोग में आसान API के माध्यम से।
उपयोग
वास्तविक समय डेटा अपडेट
सरल एप्लिकेशन राज्य प्रबंधन
फॉर्म राज्य प्रबंधन
क्रॉस-विजेट संचार
डायनामिक यूआई रेंडरिंग
मुख्य विशेषताएँ
प्रतिक्रियाशील अवस्था मूलतत्व
न्यूनतम बॉयलरप्लेट
परिष्कृत पुनर्निर्माण
क्रॉस-प्लेटफ़ॉर्म समर्थन
Flutter के साथ आसान एकीकरण
हल्का निर्भरता
इनके लिए उपयुक्त
छोटे से मध्यम आकार के Flutter ऐप्स
सरलता की खोज करने वाले विकासकर्ता
भारी अवस्था प्रबंधन से बचने वाले परियोजनाएँ
प्रोटोटाइपिंग और त्वरित विकास
रखरखाव को निर्धारित करने वाली टीमें
विचार योग्य बातें
बहुत बड़े पैमाने की अवस्था की आवश्यकता के लिए उपयुक्त नहीं
सीमित निर्मित विकास उपकरण
कोई निर्मित स्थायित्व नहीं
राज्य जीवनचक्र को हस्तकला से प्रबंधित करने की आवश्यकता है
मूल README
संबंधित सोर्स रिपॉज़िटरी के मूल README का स्नैपशॉट। नवीनतम सामग्री के लिए रिपॉज़िटरी देखें।
Overview
A Beacon is a reactive primitive(signal) and simple state management solution for Dart and Flutter; state_beacon leverages the node coloring technique created by Milo Mighdoll and used in the latest versions of SolidJS and reactively.
Flutter web demo(source): https://flutter-beacon.surge.sh/
All examples: https://github.com/zupat/dart_beacon/tree/main/examples
Installation
dart pub add state_beacon
Usage
import'package:flutter/material.dart';
import'package:state_beacon/state_beacon.dart';
final name = Beacon.writable("Bob");
classProfileCardextendsStatelessWidget{
constProfileCard({super.key});
@overrideWidgetbuild(BuildContext context) {
// rebuilds whenever the name changesreturnText(name.watch(context));
}
}
Using an asynchronous function
final counter = Beacon.writable(0);
// The future will be recomputed whenever the counter changesfinal futureCounter = Beacon.future(() async {
final count = counter.value;
returnawaitfetchData(count);
});
Future<String> fetchData(int count) async {
awaitFuture.delayed(Duration(seconds: count));
return'$count second has passed.';
}
classFutureCounterextendsStatelessWidget{
constFutureCounter({super.key});
@overrideWidgetbuild(BuildContext context) {
returnswitch (futureCounter.watch(context)) {
AsyncData<String>(value: final v) => Text(v),
AsyncError(error: final e) => Text('$e'),
_ => constCircularProgressIndicator(),
};
}
}
Features
Beacon.writable: Mutable beacon that allows both reading and writing.
Beacon.readable: Immutable beacon that only emit values, ideal for readonly data.
Beacon.derived: Derive values from other beacons, keeping them reactively in sync.
Chaining Beacons: Seamlessly chain beacons to create sophisticated reactive pipelines, combining multiple functionalities for advanced value manipulation and control.
A WritableBeacon is a mutable reactive value that notifies listeners when its value changes. You might think it's just a ValueNotifier, but the power in beacons/signals is their composability.
final counter = Beacon.writable(0);
counter.value = 10;
print(counter.value); // 10
Beacon.lazyWritable:
Like Beacon.writable but behaves like a late variable. It must be set before it's read.
This is useful for exposing a WritableBeacon's value to consumers without allowing them to modify it. This is the superclass of all beacons.
final _internalCounter = Beacon.writable(10);
// Expose the beacon's value without allowing it to be modifiedReadableBeacon<int> get counter => _internalCounter;
Beacon.derived:
A DerivedBeacon is composed of other beacons. It automatically tracks any beacons accessed within its closure and will recompute its value when one of them changes.
These beacons are lazy and will only compute their value when accessed, subscribed to or being watched by a widget or an effect.
Example:
final age = Beacon.writable(18);
final canDrink = Beacon.derived(() => age.value >= 21);
canDrink.subscribe((value) {
print(value); // Outputs: false
});
// Outputs: false
age.value = 22;
// the derived beacon will be updated and the subscribers are notified// Outputs: true
Beacon.effect:
An effect is just a function that will re-run whenever one of its
dependencies change.
Any beacon accessed within the effect will be tracked as a dependency. A change to the value of any of the tracked beacons will trigger the effect to re-run.
An effect is scheduled to run immediately after creation.
final age = Beacon.writable(15);
// this effect runs immediately and whenever age changesBeacon.effect(() {
if (age.value >= 18) {
print("You can vote!");
} else {
print("You can't vote yet");
}
});
// Outputs: "You can't vote yet"
age.value = 20; // Outputs: "You can vote!"
Beacon.future:
Creates a FutureBeacon whose value is derived from an asynchronous computation.
This beacon will recompute its value every time one of its dependencies change.
The result is wrapped in an AsyncValue, which can be in one of four states: idle, loading, data, or error.
If manualStart is true (default: false), the beacon will be in the idle state and the future will not execute until start() is called. Calling start() on a beacon that's already started will have no effect.
If shouldSleep is true(default), the callback will not execute if the beacon is no longer being watched.
It will resume executing once a listener is added or its value is accessed.
This means that it will enter the loading state when woken up.
NB: You can access the last successful data while the beacon is in the loading or error state using myFutureBeacon.lastData. Calling lastdata while in the data state will return the current value.
[!IMPORTANT]
Only beacons accessed before the async gap will be tracked as dependencies. See pitfalls for more details.
Example:
final pageNum = Beacon.writable(1);
// The future will be recomputed whenever the counter changesfinal pageArticles = Beacon.future(() async {
final currentPage = pageNum.value;
final articles = await articleService.getByPage(currentPage)
return articles;
});
classArticlesPageextendsStatelessWidget{
constArticlesPage({super.key});
@overrideWidgetbuild(BuildContext context) {
returnswitch (pageArticles.watch(context)) {
AsyncData data => ArticleList(data.value),
AsyncError(error: final e) => Text('$e'),
AsyncLoading() || AsyncIdle() => constCircularProgressIndicator(),
};
}
}
Can be transformed into a future with myFutureBeacon.toFuture()
This can useful when a FutureBeacon depends on another FutureBeacon.
This functionality is also available to StreamBeacons.
final isAdminBeacon = Beacon.writable(false);
var firstName = Beacon.future(() async {
awaitFuture.delayed(k10ms);
return'Sally';
});
var lastName = Beacon.future(() async {
awaitFuture.delayed(k10ms);
return'Smith';
});
var fullName = Beacon.future(() async {
// wait for the future to complete// we don't have to manually handle all the statesfinal [fname, lname] = awaitFuture.wait(
[
firstName.toFuture(),
lastName.toFuture(),
],
);
return'$fname$lname';
});
FutureBeacon.overrideWith:
Replaces the current callback and resets the beacon by running the new callback.
The updateWith method allows you to update a FutureBeacon's value with the provided callback. This differs from overrideWith because it updates the value only once, while overrideWith replaces the original callback supplied to the beacon.
Future<List<Todo>> loadTodos() async { ... }
Future<List<Todo>> addTodo(Todo newTodo) async {
await todoService.addTodo(newTodo);
final currentTodos = todosBeacon.lastData ?? [];
return [newTodo, ...currentTodos];
}
final todosBeacon = Beacon.future(() => loadTodos());
// Later, add a new todo without refetching all todosawait todosBeacon.updateWith(() => addTodo(newTodo));
// You can also provide an optimistic result// which will be set immediately while the future is being resolved.final optimisticTodos = [newTodo, ...todosBeacon.lastData ?? []];
await todosBeacon.updateWith(
() => addTodo(newTodo),
optimisticResult: optimisticTodos,
);
Properties:
All these methods are also available to StreamBeacons.
isIdle
isLoading
isIdleOrLoading
isData
isError
lastData: Returns the last successful data value or null. This is useful when you want to display the last valid value while refreshing.
Methods:
All these methods with the exception on reset() and overrideWith() are also available to StreamBeacons.
start(): Starts the future if it's in the idle state.
reset(): Resets the beacon by running the callback again. This will enter the loading state immediately.
unwrapValue(): Returns the value if the beacon is in the data state. This will throw an error if the beacon is not in the data state.
unwrapValueOrNull(): This is like unwrapValue() but it returns null if the beacon is not in the data state.
toFuture(): Returns a future that completes with the value when the beacon is in the data state. This will throw an error if the beacon is not in the data state.
overrideWith(): Replaces the current callback and resets the beacon by running the new callback.
updateWith(): Updates the beacon with the result of the provided future callback.
BeaconGroup:
An alternative to the global beacon creator ie: Beacon.writable(0); that
keeps track of all beacons and effects created so they can be disposed/reset together.
This is useful when you're creating multiple beacons in a stateful widget or controller class
and want to dispose them together. See BeaconController.
final myGroup = BeaconGroup();
final name = myGroup.writable('Bob');
final age = myGroup.writable(20);
myGroup.effect(() {
print(name.value); // Outputs: Bob
});
age.value = 21;
name.value = 'Alice';
myGroup.resetAll(); // reset beacons but does nothing to the effectprint(name.value); // Bobprint(age.value); // 20
myGroup.disposeAll();
print(name.isDisposed); // trueprint(age.isDisposed); // true// All beacons and effects are disposed
BeaconController
An abstract mixin class that automatically disposes all beacons and effects created within it. This can be used to create a controller that manages a group of beacons. use the included BeaconGroup(B.writable()) instead of Beacon.writable() to create beacons and effects.
NB: All beacons must be created as a late variable.
Dependency injection refers to the process of providing an instance of a Beacon or BeaconController to your widgets. state_beacon ships with a lightweight dependency injection library called lite_ref that makes it easy and ergonomic to do this while also managing disposal of both.
NB: You can use another DI library such as Provider.
In the example below, the controller will be disposed when the CounterText is unmounted:
You can also use Ref.scoped if you wish to provide a top level beacon without putting it in a controller. The beacon will be properly disposed when all widgets that use it are unmounted.
final countRef = Ref.scoped((ctx) => Beacon.writable(0));
final doubledCountRef = Ref.scoped((ctx) => Beacon.derived(() => countRef(ctx).value * 2));
classCounterTextextendsStatelessWidget{
constCounterText({super.key});
@overrideWidgetbuild(BuildContext context) {
final count = countRef.watch(context);
final doubledCount = doubledCountRef.watch(context);
returnText('$count x 2 = $doubledCount');
}
}
[!NOTE]
Even though this is possible, it is recommended to use BeaconControllers whenever possible. In cases where you only need a single beacon, this can be a convenient way to provide it to a widget.
Other Beacons
Beacon.stream:
Creates a StreamBeacon from a given stream.
When a dependency changes, the beacon will unsubscribe from the old stream and subscribe to the new one.
This beacon updates its value based on the stream's emitted values.
The emitted values are wrapped in an AsyncValue, which can be in one of 4 states:idle, loading, data, or error.
If shouldSleep is true(default), it will unsubscribe from the stream if it's no longer being watched.
It will resubscribe once a listener is added or its value is accessed.
This means that it will enter the loading state when woken up.
Can be transformed into a future with mystreamBeacon.toFuture():
Like Beacon.stream, but it doesn't wrap the value in an AsyncValue.
When a dependency changes, the beacon will unsubscribe from the old stream and subscribe to the new one.
If shouldSleep is true(default), it will unsubscribe from the stream if it's no longer being watched.
It will resubscribe once a listener is added or its value is accessed.
One of the following must be true if an initial value isn't provided:
The type is nullable
isLazy is true (beacon must be set before it's read from)
Creates a DebouncedBeacon that will delay updates to its value based on the duration. This is useful when you want to wait until a user has stopped typing before performing an action.
var query = Beacon.debounced('', duration: Duration(seconds: 1));
query.subscribe((value) {
print(value); // Outputs: 'apple' after 1 second
});
// simulate user typing
query.value = 'a';
query.value = 'ap';
query.value = 'app';
query.value = 'appl';
query.value = 'apple';
// after 1 second, the value will be updated to 'apple'
Beacon.throttled:
Creates a ThrottledBeacon that will limit the rate of updates to its value based on the duration.
If dropBlocked is true(default), values will be dropped while the beacon is blocked, otherwise, values will be buffered and emitted one by one when the beacon is unblocked.
const k10ms = Duration(milliseconds: 10);
var beacon = Beacon.throttled(10, duration: k10ms);
beacon.set(20);
expect(beacon.value, equals(20)); // first update allowed
beacon.set(30);
expect(beacon.value, equals(20)); // too fast, update ignoredawaitFuture.delayed(k10ms * 1.1);
beacon.set(30);
expect(beacon.value, equals(30)); // throttle time passed, update allowed
Beacon.filtered:
Creates a FilteredBeacon that will only updates its value if it passes the filter criteria.
The filter function receives the previous and new values as arguments.
The filter function can also be changed using the setFilter method.
Simple Example:
// only positive values are allowedvar pageNum = Beacon.filtered(10, filter: (prev, next) => next > 0);
pageNum.value = 20; // update is allowed
pageNum.value = -5; // update is ignored
Example when filter function depends on another beacon:
In this example, posts is a derived future beacon that will fetch the posts whenever pageNum changes.
We want to prevent the user from changing pageNum while posts is loading.
var pageNum = Beacon.filtered(1); // we will set the filter function laterfinal posts = Beacon.future(() => Repository.getPosts(pageNum.value));
// can't change pageNum while loading
pageNum.setFilter((prev, next) => !posts.isLoading);
Creates an UndoRedoBeacon that allows undoing and redoing changes to its value.
var age = Beacon.undoRedo(0, historyLimit: 10);
age.value = 10;
age.value = 20;
age.undo(); // Reverts to 10
age.redo(); // Goes back to 20
Beacon.progress:
Creates a ProgressBeacon that emits values periodically based on progress (0.0 to 1.0).
This beacon is useful for creating progress bars, timers, or animations.
The onProgress callback receives the current progress (0.0 to 1.0) and returns the value to be emitted.
If loop is true, the progress will reset to 0.0 after reaching 1.0 and continue.
You can control the execution with start(), pause(), resume(), and stop().
progressBar.pause();
// ...
progressBar.resume();
// ...
progressBar.start(); // restarts progress from 0.0// ...
progressBar.stop(); // stops the progress and resets elapsed time
Beacon.bufferedCount:
Creates a BufferedCountBeacon that collects and buffers a specified number
of values. Once the count threshold is reached, the beacon's value is updated
with the list of collected values and the buffer is reset.
This beacon is useful in scenarios where you need to aggregate a certain
number of values before processing them together.
var countBeacon = Beacon.bufferedCount<int>(3);
countBeacon.subscribe((values) {
print(values);
});
countBeacon.add(1);
countBeacon.add(2);
countBeacon.add(3); // Triggers update and prints [1, 2, 3]
You may also access the currentBuffer as a readable beacon.
See it in use in the konami example;
Beacon.bufferedTime:
Creates a BufferedTimeBeacon that collects values over a specified time duration.
Once the time duration elapses, the beacon's value is updated with the list of
collected values and the buffer is reset.
var timeBeacon = Beacon.bufferedTime<int>(duration: Duration(seconds: 5));
timeBeacon.subscribe((values) {
print(values);
});
timeBeacon.add(1);
timeBeacon.add(2);
// After 5 seconds, it will output [1, 2]
Beacon.list:
The ListBeacon provides methods to add, remove, and update items in the list and notifies listeners without having to make a copy.
NB: The previousValue and current value will always be the same because the same list is being mutated. If you need access to the previousValue, use Beacon.writable([]) instead.
An AsyncValue is a wrapper around a value that can be in one of four states:idle, loading, data, or error.
This is the value type of FutureBeacons,FutureBeacons and StreamBeacons.
Casts this [AsyncValue] to [AsyncData] and return its value. This will throw an error if the value is not an [AsyncData].
var name = AsyncData('Bob');
print(name.unwrap()); // Outputs: Bob
name = AsyncLoading();
print(name.unwrap()); // Throws error
AsyncValue.lastData:
Returns the latest valid data value or null. This is useful when you want to display the last valid value while loading new data.
var myBeacon = Beacon.future(() async {
returnawaitFuture.delayed(Duration(seconds: 1), () => 'Hello');
});
print(myBeacon.value); // Outputs AsyncLoading immediatelyprint(myBeacon.value.lastData); // Outputs null as there is no valid data yetawaitFuture.delayed(Duration(seconds: 1));
print(myBeacon.value.lastData); // Outputs 'Hello'
myBeacon.reset();
print(myBeacon.value); // Outputs AsyncLoadingprint(myBeacon.value.lastData); // Outputs 'Hello' as the last valid data when in loading state
AsyncValue.tryCatch:
Executes the future provided and returns [AsyncData] with the result
if successful or [AsyncError] if an exception is thrown.
Supply an optional [WritableBeacon] that will be set throughout the
various states.
Supply an optional [optimisticResult] that will be set while loading, instead of [AsyncLoading].
Future<String> fetchUserData() {
// Imagine this is a network request that might throw an errorreturnFuture.delayed(Duration(seconds: 1), () => 'User data');
}
beacon.value = AsyncLoading();
beacon.value = awaitAsyncValue.tryCatch(fetchUserData);
You can also pass the beacon as a parameter.
loading,data and error states,
as well as the last successful data will be set automatically.
awaitAsyncValue.tryCatch(fetchUserData, beacon: beacon);
// or use the extension method.await beacon.tryCatch(fetchUserData);
Creates and manages a family of related Beacons based on a single creation function.
This class provides a convenient way to handle related
beacons that share the same creation logic but have different arguments.
Type Parameters:
T: The type of the value emitted by the beacons in the family.
Arg: The type of the argument used to identify individual beacons within the family.
BeaconType: The type of the beacon in the family.
If cache is true, created beacons are cached. Default is false.
Example:
final postContentFamily = Beacon.family(
(String id) {
returnBeacon.future(() async {
returnawaitRepository.getPostContent(id);
});
},
);
final postContent = postContentFamily('post-1');
final postContent = postContentFamily('post-2');
postContent.subscribe((value) {
print(value); // Outputs: post content
});
Properties and Methods:
myBeacon.value:
The current value of the beacon. This beacon will be registered as a dependency if accessed within a derived beacon or an effect. Aliases: myBeacon(), myBeacon.call().
myBeacon.peek():
Returns the current value of the beacon without registering it as a dependency.
myBeacon.watch(context):
Returns the current value of the beacon and rebuilds the widgets whenever the beacon is updated.
final name = Beacon.writable("Bob");
classProfileCardextendsStatelessWidget{
@overrideWidgetbuild(BuildContext context) {
// rebuilds whenever the name changesreturnText(name.watch(context));
}
}
myBeacon.observe(context,callback):
Executes the callback (side effect) whenever the beacon is updated. eg: Show a snackbar when the value changes.
final name = Beacon.writable("Bob");
classProfileCardextendsStatelessWidget{
@overrideWidgetbuild(BuildContext context) {
name.observe(context, (prev, next) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('name changed from $prev to $next')),
);
});
returnText(name.watch(context));
}
}
myBeacon.subscribe():
Subscribes to the beacon and listens for changes to its value.
This returns a stream that emits the beacon's value whenever it changes.
myWritable.wrap(anyBeacon):
Wraps an existing beacon and consumes its values
Supply a (then) function to customize how the emitted values are
processed.
var bufferBeacon = Beacon.bufferedCount<String>(10);
var count = Beacon.writable(5);
// Wrap the bufferBeacon with the readableBeacon and provide a custom transformation.
bufferBeacon.wrap(count, then: (value) {
// Custom transformation: Convert the value to a string and add it to the buffer.
bufferBeacon.add(value.toString());
});
print(bufferBeacon.buffer); // Outputs: ['5']
count.value = 10;
print(bufferBeacon.buffer); // Outputs: ['5', '10']
This method is available on all writable beacons, including BufferedBeacons; and can wrap any beacon since all beacons are readable.
myWritable.ingest(anyStream):
This functions like .wrap() but it's specifically for streams. It listens to the stream and updates the beacon's value with the emitted values.
final beacon = Beacon.writable(0);
final myStream = Stream.fromIterable([1, 2, 3]);
beacon.ingest(myStream);
beacon.subscribe((value) {
print(value); // Outputs: 1, 2, 3
});
mybeacon.next():
Listens for the next value emitted by this Beacon and returns it as a Future.
This method subscribes to this Beacon and waits for the next value
that matches the optional [filter] function. If [filter] is provided and
returns false for a emitted value, the method continues waiting for the
next value that matches the filter. If no [filter] is provided,
the method completes with the first value received.
If this is a lazy beacon and it's disposed before a value is emitted,
the future will be completed with an error if a [fallback] value is not provided.
final age = Beacon.writable(20);
Timer(Duration(seconds: 1), () => age.value = 21;);
final nextAge = await age.next(); // returns 21 after 1 second
mybeacon.toListenable():
Returns a ValueListenable that emits the beacon's value whenever it changes.
mybeacon.toValueNotifier():
Returns a ValueNotifier that emits the beacon's value whenever it changes. Any mutations to the ValueNotifier will be reflected in the beacon. The ValueNotifier will be disposed when the beacon is disposed.
mybeacon.dispose():
Disposes the beacon and releases all resources.
mybeacon.onDispose():
Registers a callback to be called when the beacon is disposed. Returrns a function that can be called to unregister the callback.
Chaining methods:
Seamlessly chain beacons to create sophisticated reactive pipelines, combining multiple functionalities for advanced value manipulation and control.
// every write to this beacon will be filtered then debounced.final searchQueryText = Beacon.writable('');
final searchQuery = searchQueryText.filter((prev, next) => next.length > 2).debounce(duration: k500ms);
[!WARNING] buffer and bufferTime cannot be mid-chain. If they are used, they MUST be the last in the chain.
// GOOD
someBeacon.filter().buffer(10);
// BAD
someBeacon.buffer(10).filter();
[!NOTE]
When map returns a different type, writes to the returned beacon will not be re-routed to the original beacon. In the example below, writes to filteredBeacon will NOT be re-routed to count because map returns a String; which means the type of the returned beacon is FilteredBeacon<String> and count holds an int.
final count = Beacon.writable(0);
final filteredBeacon = count.map((v) => '$v').filter((_, n) => n.length > 1);
Set the global BeaconObserver instance to get notified of all beacon creation, updates and disposals. You can also see when a derived beacon or effect starts/stops watching a beacon.
You can create your own observer by implementing BeaconObserver or use the provided logging observer, which logs to the console. Provide a name to your beacons to make it easier to identify them in the logs.
BeaconObserver.instance = LoggingObserver(); // or BeaconObserver.useLogging()var a = Beacon.writable(10, name: 'a');
var b = Beacon.writable(20, name: 'b');
var c = Beacon.derived(() => a() * b(), name: 'c');
Beacon.effect(
() {
print('c: ${c.value}');
},
name: 'printEffect',
);
This will log:
Beacon created: a
Beacon created: b
Beacon created: c
"printEffect"is watching "c""c"is watching "a""c"is watching "b""c" was updated:
old: nullnew: 200
"c" stopped watching "a""c" stopped watching "b""c" was disposed
"printEffect" stopped watching c
Disposal
When a beacon is disposed, all downstream derived beacons and effects will be disposed as well.
A beacon cannot be updated after it's disposed. An assertion error will be thrown if you try to update a disposed beacon.
A warning will be logged in debug mode if you try to access the value of a disposed beacon.
A beacon should be disposed when it's no longer needed to free up resources.
In the example below, when a is disposed, c and effect will also be disposed.
ab\/\/c|
|
effect
final a = Beacon.writable(10);
final b = Beacon.writable(10);
final c = Beacon.derived(() => a.value * b.value);
Beacon.effect(() => print(c.value));
//...//
a.dispose();
expect(a.isDisposed, true);
expect(c.isDisposed, true);
// effect is also disposed
BeaconScheduler:
Effects and Subscriptions are not synchronous, their execution is controlled by a scheduler. When a dependency of an effect changes, it is added to a queue and the scheduler decides when is the best time to flush the queue. By default, the queue is flushed with a DARTVM microtask which runs on the next loop; this can be changed by setting a custom scheduler.
A 60fps scheduler is included, this limits processing effects to 60 times per second. This can be done by calling BeaconScheduler.use60FpsScheduler(); in the main function. You can also create your own custom scheduler for more advanced use cases. eg: Gaming: Synchronize flushing with your game loop.
When testing synchronous code, it is necessary to flush the queue manually. This can be done by calling BeaconScheduler.flush(); in your test.
[!NOTE]
When writing widget tests, manual flushing isn't needed. The queue is automatically flushed when you call tester.pumpAndSettle().
final a = Beacon.writable(10);
var called = 0;
// effect is queued for execution. The scheduler decides when to run the effectBeacon.effect(() {
print("current value: ${a.value}");
called++;
});
// manually flush the queue to run the all effect immediatelyBeaconScheduler.flush();
expect(called, 1);
a.value = 20; // effect will be queued again.BeaconScheduler.flush();
expect(called, 2);
Testing
Beacons can expose a Stream with the .stream method. This can be used to test the state of a beacon over time with existing StreamMatchers.
A mixin for StatefulWidget's State class that automatically disposes all beacons and effects created within it.
classMyControllerextendsStatefulWidget{
constMyController({super.key});
@overrideState<MyController> createState() => _MyControllerState();
}
class_MyControllerStateextendsState<MyController>
withBeaconControllerMixin{
// NO need to dispose these manuallylatefinal count = B.writable(0);
latefinal doubledCount = B.derived(() => count.value * 2);
@overrideWidgetbuild(BuildContext context) {
returnContainer();
}
}
TextEditingBeacon
A beacon that wraps a TextEditingController. All changes to the controller are reflected in the beacon and vice versa.
final beacon = TextEditingBeacon();
final controller = beacon.controller;
controller.text = 'Hello World';
print(beacon.value.text); // Outputs: Hello World
Pitfalls
When using Beacon.future, only beacons accessed before the async gap(await) will be tracked as dependencies.
final counter = Beacon.writable(0);
final doubledCounter = Beacon.derived(() => counter.value * 2);
final futureCounter = Beacon.future(() async {
// This will be tracked as a dependency because it's accessed before the async gapfinal count = counter.value;
awaitFuture.delayed(Duration(seconds: count));
// This will NOT be tracked as a dependency because it's accessed after `await`final doubled = doubledCounter.value;
return'$count x 2 = $doubled';
});
When a future depends on multiple future/stream beacons
DON'T:
final futureCounter = Beacon.future(() async {
// in this instance lastNameStreamBeacon will not be tracked as a dependency// because it's accessed after the async gapfinal firstName = await firstNameFutureBeacon.toFuture();
final lastName = await lastNameStreamBeacon.toFuture();
return'Fullname is $firstName$lastName';
});
DO:
final futureCounter = Beacon.future(() async {
// store the futures before the async gap ie: don't use awaitfinal firstNameFuture = firstNameFutureBeacon.toFuture();
final lastNameFuture = lastNameStreamBeacon.toFuture();
// wait for the futures to completefinal (String firstName, String lastName) = await (firstNameFuture, lastNameFuture).wait;
return'Fullname is $firstName$lastName';
});