Line data Source code
1 : import 'package:flutter/widgets.dart'; 2 : import 'package:property_change_notifier/property_change_notifier.dart'; 3 : 4 : typedef PropertyChangeBuilder<T> = Widget Function(BuildContext, T, Set<Object>); 5 : 6 : /// A widget-based listener for cases where a [BuildContext] is hard to access, or if you prefer this kind of API. 7 : /// To register the widget to be rebuilt only on specific property changes, provide a [properties] parameter. 8 : /// 9 : /// Access both the model value and the changed properties via the [builder] callback: 10 : /// ```dart 11 : /// PropertyChangeConsumer<MyModel>( 12 : /// properties: ['foo', 'bar'], 13 : /// builder: (context, model, properties) { 14 : /// return Column( 15 : /// children: [ 16 : /// Text('$properties were changed!'), 17 : /// RaisedButton( 18 : /// child: Text('Update foo'), 19 : /// onPressed: () { 20 : /// model.foo = DateTime.now().toString(); 21 : /// }, 22 : /// ), 23 : /// RaisedButton( 24 : /// child: Text('Update bar'), 25 : /// onPressed: () { 26 : /// model.bar = DateTime.now().toString(); 27 : /// }, 28 : /// ), 29 : /// ], 30 : /// ); 31 : /// }, 32 : /// ); 33 : /// ``` 34 : class PropertyChangeConsumer<T extends PropertyChangeNotifier> extends StatelessWidget { 35 : final Iterable<Object> properties; 36 : final PropertyChangeBuilder<T> builder; 37 : 38 1 : PropertyChangeConsumer({ 39 : Key key, 40 : this.properties, 41 : @required this.builder, 42 1 : }) : assert(builder != null), 43 1 : super(key: key); 44 : 45 1 : @override 46 : Widget build(BuildContext context) { 47 2 : final model = PropertyChangeProvider.of<T>(context, properties: this.properties, listen: true); 48 3 : return this.builder(context, model.value, model.properties); 49 : } 50 : }