shared_state 1.0.0
shared_state: ^1.0.0 copied to clipboard
Providing a shared state store ability for dart. With `shared_state_store`, developers can share state in one isolate easily and can be notified when state changed. Also, it can be a rescue for handle [...]
Providing an ability of sharing state environment. Used for multiple life scope sharing state and dependency injection.
Features #
- multiple life scope sharing: eg, Sharing state over seperated pages and modules.
- subscribing specific value changed: eg, Observing
loginkey to get whether logged in or logged out. - Decoupling specific dependency implementation: eg,
module sub Aneeds to provide the ability to pull up an advertisement from a certain vendor, but it will be determine frommodule S. We can define an interface that can be declared throughmodule sub A, andmodule Scan be implement the interface and injected throughSharedState.
Getting started #
Pure dart 3 module, no other dependency
dependencies:
shared_state: ^${latestVersion}
Usage #
basic usage #
Assign and read
const key = 'some awesome key';
SharedState().set<String>(key, 'my great value');
final v = SharedState().get<String>(key);
if (v != null) {
// using my great value
}
// cleanup
SharedState().invalid(key);
Observing key change
const loginStatusKey = 'login_status';
// register event change
SharedState().onKeyChange<bool>(loginStatusKey).listen((event) {
// got status changed
if (event == true) {
// value set to true
}
else if (event == false) {
// value set to false
}
else {
// value was set to null
}
});
SharedState().set<bool>(loginStatusKey, false);
Dependency injection #
// submodule A
const String incrementorKey = 'Incrementor';
abstract interface class Incrementor {
void increment();
int get value;
}
class IncrementorUsageClass {
void foo() {
// fetch implementation from shared state
final incrementor = SharedState().get<Incrementor>(incrementorKey);
if (incrementor != null) {
print('value: ${incrementor.value}');
}
}
}
// container/caller module
import 'submodule a';
void main() {
SharedState().set<Incrementor>(incrementorKey, IncrementorImpl());
final usageClass = IncrementorUsageClass();
// call usage class here
usageClass.foo();
}
class IncrementorImpl implements Incrementor {
int _v;
int get value => _v;
void increment() {
_v += 1;
}
}
Additional information #
⚠️ caution: Not suit for multiple isolate sharing state