Skip to content

Repository files navigation

pub package

Shared Value

A wrapper over InheritedModel, this module allows you to easily manage global state in flutter apps.

At a high level, SharedValue puts your variables in an intelligent "container" that is flutter-aware.

It can be viewed as a low-boilerplate generalization of the Provider state management solution.

Usage

1. Initialize

IMPORTANT: Always declare SharedValue variables as final, so you don't accidentally over-write the SharedValue object (which you generally don't want to do.)

// This global SharedValue can be shared across the entire app// IMPORTANT: Variable declared as finalfinalSharedValue<int> counter =SharedValue(
// initial value
value:0,
);
voidmain() {
runApp(
// Don't forget this bit of initialization code!SharedValue.wrapApp(
MyApp(),
),
);
}

2. Use

Unlike other state management solutions, SharedValue works everywhere you'd expect dart code to work, even without a BuildContext.

voidmain() {
// Read [counter]print(counter.$);
// Update [counter]
counter.$ +=1;
}
// Use [counter] in widgets, and let SharedValue do the rest.Widgetbuild(BuildContext context) {
// The .of(context) bit makes this widget rebuild automaticallyint counterValue = counter.of(context);
returnText("Counter: $counterValue");
}

3. Persist

// provide a shared_prefences keyfinalSharedValue<int> counter =SharedValue(
// disk storage key for shared_preferences (optional)
key:"counter",
// autosave to shared prefs when value changes (optional)
autosave:true,
);
voidmain() async {
// Load [counter]'s value from shared preferencesawait counter.load();
// Store [counter]'s value to shared preferences (enabling `autosave` does this automatically)await counter.store();
}

Efficiency

Shared value is smart enough to only rebuild the widget that subscribes to updates using .of(context), no more, no less.

About

A straightforward way to manage global state in flutter apps.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages