父类传递给子类可以通过构造方法。
那么子类给父类呢?
答案也是构造方法 直接传递VoidCallback进来
这个VoidCallback是通过查看onPress类型得到的
import 'package:flutter/material.dart';class StateManagementDemo2 extends StatefulWidget {@override_StateManagement2State createState() => _StateManagement2State();
}class _StateManagement2State extends State {int _count = 0;void _increaseCount() {setState(() {_count += 1;});}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("StatueManagementDemo"),elevation: 0.0,),body: Counter(_count, _increaseCount),floatingActionButton: FloatingActionButton(child: Icon(Icons.add),onPressed: () {setState(() {_count += 1;});print(_count);},),);}
}class Counter extends StatelessWidget {final int count;final VoidCallback increaseCount;Counter(this.count, this.increaseCount);@overrideWidget build(BuildContext context) {return Center(child: ActionChip(label: Text('$count'),onPressed: increaseCount,),);}
}
多级别当然就是多个构造
import 'package:flutter/material.dart';class StateManagementDemo3 extends StatefulWidget {@override_StateManagement3State createState() => _StateManagement3State();
}class _StateManagement3State extends State {int _count = 0;void _increaseCount() {setState(() {_count += 1;});}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("StatueManagementDemo"),elevation: 0.0,),body: ConunterWrapper(_count, _increaseCount),floatingActionButton: FloatingActionButton(child: Icon(Icons.add),onPressed: () {setState(() {_count += 1;});print(_count);},),);}
}class ConunterWrapper extends StatelessWidget {final int count;final VoidCallback increaseCount;ConunterWrapper(this.count, this.increaseCount);@overrideWidget build(BuildContext context) {return Center(child: Counter(count, increaseCount),);}
}class Counter extends StatelessWidget {final int count;final VoidCallback increaseCount;Counter(this.count, this.increaseCount);@overrideWidget build(BuildContext context) {return Center(child: ActionChip(label: Text('$count'),onPressed: increaseCount,),);}
}
下篇博客将对这个多种数据传递进行优化