From d42db56b52657d7557664393ac1fe9a734a6b6e7 Mon Sep 17 00:00:00 2001 From: Dan Field Date: Sat, 6 Apr 2019 20:14:41 -0700 Subject: [PATCH] Add sample for ValueListenableBuilder (#30626) * Add sample for ValueListenableBuilder --- .../src/widgets/value_listenable_builder.dart | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/packages/flutter/lib/src/widgets/value_listenable_builder.dart b/packages/flutter/lib/src/widgets/value_listenable_builder.dart index 01a2889181..30a397425e 100644 --- a/packages/flutter/lib/src/widgets/value_listenable_builder.dart +++ b/packages/flutter/lib/src/widgets/value_listenable_builder.dart @@ -38,6 +38,65 @@ typedef ValueWidgetBuilder = Widget Function(BuildContext context, T value, W /// Using this pre-built child is entirely optional, but can improve /// performance significantly in some cases and is therefore a good practice. /// +/// {@tool sample} +/// +/// This sample shows how you could use a [ValueListenableBuilder] instead of +/// setting state on the whole [Scaffold] in the default `flutter create` app. +/// +/// ```dart +/// class MyHomePage extends StatefulWidget { +/// MyHomePage({Key key, this.title}) : super(key: key); +/// final String title; +/// +/// @override +/// _MyHomePageState createState() => _MyHomePageState(); +/// } +/// +/// class _MyHomePageState extends State { +/// final ValueNotifier _counter = ValueNotifier(0); +/// final Widget goodJob = const Text('Good job!'); +/// @override +/// Widget build(BuildContext context) { +/// return Scaffold( +/// appBar: AppBar( +/// title: Text(widget.title) +/// ), +/// body: Center( +/// child: Column( +/// mainAxisAlignment: MainAxisAlignment.center, +/// children: [ +/// Text('You have pushed the button this many times:'), +/// ValueListenableBuilder( +/// builder: (BuildContext context, int value, Widget child) { +/// // This builder will only get called when the _counter +/// // is updated. +/// return Row( +/// mainAxisAlignment: MainAxisAlignment.spaceEvenly, +/// children: [ +/// Text('$value'), +/// child, +/// ], +/// ); +/// }, +/// valueListenable: _counter, +/// // The child parameter is most helpful if the child is +/// // expensive to build and does not depend on the value from +/// // the notifier. +/// child: goodJob, +/// ) +/// ], +/// ), +/// ), +/// floatingActionButton: FloatingActionButton( +/// child: Icon(Icons.plus_one), +/// onPressed: () => _counter.value += 1, +/// ), +/// ); +/// } +/// } +/// ``` +/// {@end-tool} +/// /// See also: /// /// * [AnimatedBuilder], which also triggers rebuilds from a [Listenable]