简介

这个 widget 提供了共享 数据的功能

问题

当你需要分享一个数据的时候怎么做?
image.png
下面这个套娃式方法看起来不太好

  1. return A(
  2. data:data
  3. child:B(
  4. data:data
  5. child:C(
  6. data:data
  7. child:F(
  8. data:data
  9. )
  10. )
  11. )
  12. );

一个简单的例子

  1. import 'dart:math' as math;
  2. import 'package:flutter/material.dart';
  3. void main() {
  4. runApp(const MaterialApp(
  5. home: MyWidget(),
  6. ));
  7. }
  8. class MyWidget extends StatefulWidget {
  9. const MyWidget({
  10. Key? key,
  11. }) : super(key: key);
  12. @override
  13. State<MyWidget> createState() => _MyWidgetState();
  14. }
  15. class _MyWidgetState extends State<MyWidget> {
  16. Color color = Colors.red;
  17. @override
  18. Widget build(BuildContext context) {
  19. return Scaffold(
  20. body: ColorInfo(color,
  21. child: Container(
  22. child: Container(
  23. child: Column(
  24. children: const [
  25. ColorConsumer(),
  26. NotColorConsumer(),
  27. ],
  28. ),
  29. ),
  30. )),
  31. floatingActionButton: FloatingActionButton(
  32. onPressed: () {
  33. setState(() {
  34. color = Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0);
  35. });
  36. },
  37. ),
  38. );
  39. }
  40. }
  41. class ColorInfo extends InheritedWidget {
  42. const ColorInfo(
  43. this.color, {
  44. Key? key,
  45. required Widget child,
  46. }) : super(key: key, child: child);
  47. final Color color;
  48. static ColorInfo of(BuildContext context) {
  49. final ColorInfo? result = context.dependOnInheritedWidgetOfExactType<ColorInfo>();
  50. assert(result != null, 'No ColorInco found in context');
  51. return result!;
  52. }
  53. @override
  54. bool updateShouldNotify(ColorInfo old) {
  55. return old.color != color;
  56. }
  57. }
  58. // 这个消费 ColorInfo 里面的 color
  59. class ColorConsumer extends StatelessWidget {
  60. const ColorConsumer({Key? key}) : super(key: key);
  61. @override
  62. Widget build(BuildContext context) {
  63. final ColorInfo colorInfo = context.dependOnInheritedWidgetOfExactType<ColorInfo>() as ColorInfo;
  64. print('build ColorConsumer');
  65. return Expanded(child: Container(color: colorInfo.color));
  66. }
  67. }
  68. // 这个不消费 ColorInfo 里面的 color
  69. class NotColorConsumer extends StatelessWidget {
  70. const NotColorConsumer({Key? key}) : super(key: key);
  71. @override
  72. Widget build(BuildContext context) {
  73. print('build NotColorConsumer');
  74. return Expanded(child: Container());
  75. }
  76. }