前置知识 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直接传给子组件而不通过中间的父组件
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.yellow,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: CounterProvider(
child: Swaper(),
count: _counter,
increaseCount: _incrementCounter,
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class Swaper extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Counter(),
);
}
}
class Counter extends StatelessWidget {
@override
Widget build(BuildContext context) {
final int count = CounterProvider.of(context).count;
final VoidCallback increaseCount =
CounterProvider.of(context).increaseCount;
return ActionChip(
label: Text("$count"),
onPressed: increaseCount,
);
}
}
class CounterProvider extends InheritedWidget {
final int count;
final VoidCallback increaseCount;
final Widget child;
CounterProvider({this.count, this.increaseCount, this.child})
: super(child: child);
static CounterProvider of(BuildContext context) =>
context.inheritFromWidgetOfExactType(CounterProvider);
@override
bool updateShouldNotify(InheritedWidget oldWidget) {
// TODO: implement updateShouldNotify
return true;
}
}