Flutter App的Widget体系结构

时间:2018-04-04 04:35:12

标签: android ios dart flutter

我正在制作这个应用程序,但我不确定组织它的好方法。随着图片演示如下:

enter image description here

(当前):

  • 蓝色:无状态小工具=> ListView,Rows Widgets
  • 红色:有状态的小工具=>扩展小部件
  • 绿色:无状态小工具=>扩展小部件

应用程序需要做什么:数字需要在更改时自行更新(我现在不担心花哨的动画,只是过渡)。

问题:我发现更新这些数字的唯一方法是每分钟通过Timer.periodic。但是,我发现很难找到这些信息。我目前在每个Red Expanded Widget下都有我的定期计时器,但是所有这些都使用了唯一的DateTime。冗余信息是这种方法的问题。我可以在Blue ListView,Rows Widget中放置一个定期计时器。但是,每次更新都需要重新加载所有包含小部件的小部件,包括Green Expanded Widgets。

如果有任何建议或不同方式,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

Flutter的设计意味着重新加载绿色小工具并不重要;它的工作方式使它非常便宜。因此,将状态拖到包含所有文本/列/等的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),
      ],
    );
  }
}

如果以后想要让你的状态更高,你可以使用一个InheritedWidget。 (我有时会在MaterialApp上面使用一个。)Brian Egan在DartConf 2018上就这整个主题发表了精彩的演讲。 https://www.youtube.com/watch?v=zKXz3pUkw9A&list=PLOU2XLYxmsIIJr3vjxggY7yGcGO7i9BK5&index=10

相关问题