Ribir
Ribir copied to clipboard
Data Sharing with Provider
In widget-based applications, there's often a need to share data across widgets. While one approach is to pass data from parent to child widgets, this can become cumbersome in deeply nested widget trees.
To address this, we introduce the Provider
widget. This widget allows its descendants to access the data it provides, simplifying data sharing across the widget tree.
Descendants can inquire about the provider's type. If it's a state, they can also access the state's reference or its WriteRef
.
By default, the root widget should be a global provider. This is because the root widget is the application data.
use ribir::prelude::*;
let w = fn_widget! {
@Provider {
provider: Stateful::new(0i32),
@FilledButton {
@{
// Descendants can query the type of the provider
let cnt: Option<&Stateful<i32>> = Provider::of::<Stateful<i32>>(ctx!());
// Or the read ref of the state
let cnt: Option<QueryRef<i32>> = Provider::read_of::<i32>(ctx!());
// Or the write ref of the state
let cnt: Option<WriteRef<i32>> = Provider::write_of::<i32>(ctx!());
Label::new(cnt.to_string())
}
}
}
};