只有一个小部件,Flutter应用程序变得慢得多

时间:2018-02-15 15:32:31

标签: dart flutter

所以在我的应用程序中我有一个简单的评级功能,为了实现这一点,我构建了一个简单的星形小部件,其中“填充”参数为0.0-1.0,评级小部件使用一排五颗星计数相应的填。问题是,由于某些无法解释的原因,当删除特定小部件时,列表(因为它出现在列表中)会变得非常慢。这是他明星的代码:

class Star extends StatelessWidget {
  final double fill;
  final double scale;
  Star({@required this.fill, this.scale = 1.0}):
    assert(fill<=1.0 && fill >=0.0);

  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: new EdgeInsets.only(
        right: 2.5*scale,
      ),
      child: new Material(
        elevation: 2.0,
        borderRadius: new BorderRadius.circular(3.0),
        child: new Container(
          height: 14.0*scale,
          width: 14.0*scale,
          child: new Stack(
            children: <Widget>[
              new Container(
                color: Colors.blue,
                width: this.fill * 14.0*scale,
              ),
              new Center(
                child: new Material(
                  elevation: 3.0,
                  color: new Color(0x00000000),
                  child: new Icon(
                    Icons.star,
                    size: 12.0*scale,
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

对于完整评级小部件:

class Rating extends StatelessWidget {
  final double rating;
  final double scale;

  Rating({
    @required this.rating,
    this.scale = 1.0,
  })
      : assert(rating <= 5 && rating >= 0);

    @override
  Widget build(BuildContext context) {
    final List<Star> stars = new List.generate(5, (index) {
      return new Star(
        fill: _getFill(index),
        scale: scale,
      );
    });

    return new Row(
      children: stars,
    );
  }

  int _getStarsNeeded() {
    double r = rating;
    if (r <= 0)
      return 0;
    else if (r > 0 && r <= 1)
      return 1;
    else if (r > 1 && r <= 2)
      return 2;
    else if (r > 2 && r <= 3)
      return 3;
    else if (r > 3 && r <= 4)
      return 4;
    else
      return 5;
  }

  double _getEndingStarFill() {
    return (rating + 1 - _getStarsNeeded());
  }

  double _getFill(index) {
    int neededStars = _getStarsNeeded();
    if (index < neededStars - 1) {
      return 1.0;
    } else if (index == neededStars - 1) {
      return _getEndingStarFill();
    } else
      return 0.0;
  }
}

我知道这不是找到填充的最好方法,但这不是这里的情况。然而看起来很简单,让事情变得沉重。

0 个答案:

没有答案