context_ref
3.2.3, released a year ago by sonerik.dev
Provide and retrieve values scoped to a BuildContext with automatic disposal.
What it does
Allows scoping, binding, and retrieving objects directly to a BuildContext without boilerplate. Values can be automatically initialized, lazily loaded, and disposed when the context is removed from the widget tree.
AI-written summary of version 3.2.3, based on the package's README and metadata. Report an inaccuracy
Use it when
- You want a hassle-free way to scope state or objects to a BuildContext
- You need automatic cleanup and disposal of bound resources with the widget lifecycle
- You prefer extension-based hooks or context-based object access instead of traditional InheritedWidgets
Skip it when
- You need global application state independent of any BuildContext
- You are using a state management pattern that strictly forbids context lookups
Strengths
- Automatic disposal of bound objects tied to the widget lifecycle
- Minimal boilerplate compared to traditional InheritedWidget setup
- Supports lazy initialization and pre-existing value binding
Weaknesses
- Requires a root widget wrapper (`ContextRef.root`)
- Tightly coupled to the widget tree via BuildContext
Setup
- Kind
- Flutter widgets
- Effort
- Low
- Code generation
- No
- Direct dependencies
- 2
Wrap your app in a `ContextRef.root` widget and optionally wrap error handlers for better hot reload error messages.
final _stream = Ref<Stream>();
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
final stream = _stream.bind(context, () => Stream.periodic(const Duration(seconds: 1)));
return const _Child();
}
}Alternatives
Packages that do the same job and could replace context_ref.
- yx_state
A state management library for Dart and Flutter applications.
82Compare - bloc_signals_flutter
Flutter UI extensions, providers, and bindings for the bloc_signals state management library.
75Compare - riverpod
A reactive caching and data-binding framework. Riverpod makes working with asynchronous code a breeze.
99Compare - bloc_tools
Command-line tools for generating and linting bloc and cubit components.
88Compare
Works with
Packages commonly used together with context_ref: ones it builds on, ones built on it, and its own family.