Flutter 的设计意味着你重新加载绿色的 Widgets 并不重要;它的工作方式使它非常便宜。因此,将您的状态拖到包含所有文本/列/等的 StatefulWidget(现在可以是无状态的)。
这个例子展示了一种下推状态片段的方法(进入 DurationPartWidget 的构造函数)。我已经证明您可以在构建方法中进行日期数学运算。同样,您可以在 setState 中执行此操作,并创建 _AnniversaryWidgetState 的年、月等实例变量。
class AnniversaryWidget extends StatefulWidget {
final DateTime firstDate;
AnniversaryWidget(this.firstDate);
@override
State createState() {
return new _AnniversaryWidgetState();
}
}
class _AnniversaryWidgetState extends State<AnniversaryWidget> {
Timer _timer;
@override
void initState() {
super.initState();
_timer = new Timer.periodic(new Duration(seconds: 1), (Timer t) {
setState(() {});
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
DateTime now = new DateTime.now();
// todo - calculate these from now minus firstDate
int years = 0;
int months = 4;
int days = 13;
int hours = 21;
int minutes = now.difference(widget.firstDate).inMinutes % 60;
return new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new _DurationPartWidget('years', years),
new _DurationPartWidget('months', months),
new _DurationPartWidget('days', days),
new _DurationPartWidget('hours', hours),
new _DurationPartWidget('minutes', minutes),
],
),
);
}
}
class _DurationPartWidget extends StatelessWidget {
final int _numberPart;
final String _label;
_DurationPartWidget(this._label, this._numberPart);
@override
Widget build(BuildContext context) {
return new Row(
children: <Widget>[
new Text(_numberPart.toString().padLeft(2, '0')),
new Text(_label),
],
);
}
}
如果以后,您想将状态带到 Widget 树的更高位置,您可以使用 InheritedWidget。 (我有时会使用 MaterialApp 上面的一个。)Brian Egan 在 DartConf 2018 上就整个主题发表了精彩的演讲。
https://www.youtube.com/watch?v=zKXz3pUkw9A&list=PLOU2XLYxmsIIJr3vjxggY7yGcGO7i9BK5&index=10