chooyan-eng / providable

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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 and watch available.

Usage

define state class extending ValueNotifier

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];
  }
}

place Provider on a widget tree

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!

About

License:Other


Languages

Language:Dart 78.6%Language:Swift 17.3%Language:Kotlin 3.1%Language:Objective-C 1.0%