Providing an ability of sharing state environment. Used for multiple life scope sharing state and dependency injection.
- multiple life scope sharing: eg, Sharing state over seperated pages and modules.
- subscribing specific value changed: eg, Observing
login
key to get whether logged in or logged out. - Decoupling specific dependency implementation: eg,
module sub A
needs 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 S
can be implement the interface and injected throughSharedState
.
Pure dart 3
module, no other dependency
dependencies:
shared_state: ^${latestVersion}
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);
// 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;
}
}
isolate
sharing state