Guest User

Untitled

a guest
Dec 15th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. /*
  2.  
  3. The application model is shared by an InheritedWidget: ModelBinding.
  4. ModelBinding has-a Model. All of the descendants of ModelBinding can get
  5. the model with Model.of(context) and in so doing, register themselves
  6. as dependents which will be rebuilt when ModelBinding is rebuilt.
  7.  
  8. To change the shared model, the ModelBinding must be rebuilt with a new Model.
  9. Descendants of ModelBinding must be provided with a callback that rebuilds
  10. ModelBinding's stateful parent.
  11.  
  12. */
  13.  
  14. import 'package:flutter/material.dart';
  15.  
  16. class Model {
  17. const Model({ this.value = 0 });
  18.  
  19. final int value;
  20.  
  21. @override
  22. bool operator ==(Object other) {
  23. if (identical(this, other))
  24. return true;
  25. if (other.runtimeType != runtimeType)
  26. return false;
  27. final Model otherModel = other;
  28. return otherModel.value == value;
  29. }
  30.  
  31. @override
  32. int get hashCode => value.hashCode;
  33.  
  34. static Model of(BuildContext context) {
  35. final ModelBinding binding = context.inheritFromWidgetOfExactType(ModelBinding);
  36. return binding.model;
  37. }
  38. }
  39.  
  40. class ModelBinding extends InheritedWidget {
  41. ModelBinding({
  42. Key key,
  43. this.model = const Model(),
  44. Widget child,
  45. }) : assert(model != null), super(key: key, child: child);
  46.  
  47. final Model model;
  48.  
  49. @override
  50. bool updateShouldNotify(ModelBinding oldWidget) => model != oldWidget.model;
  51. }
  52.  
  53. class ViewController extends StatelessWidget {
  54. const ViewController({ Key key, this.updateModel }) : super(key: key);
  55.  
  56. final ValueChanged<Model> updateModel;
  57.  
  58. @override
  59. Widget build(BuildContext context) {
  60. return RaisedButton(
  61. onPressed: () {
  62. updateModel(Model(value: Model.of(context).value + 1));
  63. },
  64. child: Text('Hello World ${Model.of(context).value}'),
  65. );
  66. }
  67. }
  68.  
  69. class App extends StatefulWidget {
  70. @override
  71. _AppState createState() => _AppState();
  72. }
  73.  
  74. class _AppState extends State<App> {
  75. Model currentModel = Model();
  76.  
  77. void updateModel(Model newModel) {
  78. if (newModel != currentModel) {
  79. setState(() {
  80. currentModel = newModel;
  81. });
  82. }
  83. }
  84.  
  85. @override
  86. Widget build(BuildContext context) {
  87. return MaterialApp(
  88. home: ModelBinding(
  89. model: currentModel,
  90. child: Scaffold(
  91. body: Center(
  92. child: ViewController(updateModel: updateModel),
  93. ),
  94. ),
  95. ),
  96. );
  97. }
  98. }
  99.  
  100. void main() {
  101. runApp(App());
  102. }
Add Comment
Please, Sign In to add comment