前置知识 Mixin 概念
https://juejin.im/post/5bb204d3e51d450e4f38e2f6

build
https://juejin.im/post/5c665cb651882562914ec153

key
https://blog.csdn.net/weixin_43901866/article/details/88980514

状态管理文章
https://juejin.im/post/5de1dd446fb9a071817bfc6e
https://juejin.im/post/5d00a84fe51d455a2f22023f
https://www.bilibili.com/video/av65343050?p=10

不使用 model 的传值

祖组件将构造函数与count直接传给子组件而不通过中间的父组件

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. return MaterialApp(
  7. debugShowCheckedModeBanner: false,
  8. title: 'Flutter Demo',
  9. theme: ThemeData(
  10. primarySwatch: Colors.yellow,
  11. ),
  12. home: MyHomePage(title: 'Flutter Demo Home Page'),
  13. );
  14. }
  15. }
  16. class MyHomePage extends StatefulWidget {
  17. MyHomePage({Key key, this.title}) : super(key: key);
  18. final String title;
  19. @override
  20. _MyHomePageState createState() => _MyHomePageState();
  21. }
  22. class _MyHomePageState extends State<MyHomePage> {
  23. int _counter = 0;
  24. void _incrementCounter() {
  25. setState(() {
  26. _counter++;
  27. });
  28. }
  29. @override
  30. Widget build(BuildContext context) {
  31. return Scaffold(
  32. appBar: AppBar(
  33. title: Text(widget.title),
  34. ),
  35. body: CounterProvider(
  36. child: Swaper(),
  37. count: _counter,
  38. increaseCount: _incrementCounter,
  39. ),
  40. floatingActionButton: FloatingActionButton(
  41. onPressed: _incrementCounter,
  42. tooltip: 'Increment',
  43. child: Icon(Icons.add),
  44. ), // This trailing comma makes auto-formatting nicer for build methods.
  45. );
  46. }
  47. }
  48. class Swaper extends StatelessWidget {
  49. @override
  50. Widget build(BuildContext context) {
  51. return Container(
  52. child: Counter(),
  53. );
  54. }
  55. }
  56. class Counter extends StatelessWidget {
  57. @override
  58. Widget build(BuildContext context) {
  59. final int count = CounterProvider.of(context).count;
  60. final VoidCallback increaseCount =
  61. CounterProvider.of(context).increaseCount;
  62. return ActionChip(
  63. label: Text("$count"),
  64. onPressed: increaseCount,
  65. );
  66. }
  67. }
  68. class CounterProvider extends InheritedWidget {
  69. final int count;
  70. final VoidCallback increaseCount;
  71. final Widget child;
  72. CounterProvider({this.count, this.increaseCount, this.child})
  73. : super(child: child);
  74. static CounterProvider of(BuildContext context) =>
  75. context.inheritFromWidgetOfExactType(CounterProvider);
  76. @override
  77. bool updateShouldNotify(InheritedWidget oldWidget) {
  78. // TODO: implement updateShouldNotify
  79. return true;
  80. }
  81. }