providable
Extremely tiny wrapper package of InheritedWidget
.
It's NOT for production usage but a learning generic state management mechanisms purpose.
Features
- Provide value to descendant widgets.
read
andwatch
available.
Usage
ValueNotifier
define state class extending An example ArticleState
class preserving a list of Article
is shown below.
class ArticlesState extends ValueNotifier<List<Article>> {
ArticlesState() : super(<Article>[]);
List<Article> get articles => value;
void add(Article newArticle) {
value = [...value, newArticle];
}
}
Provider
on a widget tree
place Make sure Provider
have to be placed at ancestor position than user widgets.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Provider(
create: () => ArticlesState(),
child: const ArticlesPage(),
),
);
}
read / watch it from a widget
You can observe the state with Provider.watch<T>()
and read the state with Provider.read<T>()
.
final articles = Provider.watch<ArticlesState>(context).articles;
onPressed: () {
Provider.read<ArticlesState>(context).add(Article(
'TITLE: time at ${DateTime.now()}',
'chooyan',
));
},
That's it!