编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Flutter - 动画条形图

wxchong 2024-06-21 14:25:19 开源技术 11 ℃ 0 评论

Flutter团队目前开始有关动画的视频系列(https://www.youtube.com/watch?v=IVTjpW3W33s)。由于它没有涵盖第三方动画库,因此我想分享一个使用简单动画包(https://pub.dev/packages/simple_animations)创建的示例。

我们要制作一个条形图的动画,其中每个条形分别设置动画。这些条以相同的速度生长。这意味着每个动画都有不同的动画持续时间

我们首先创建一个小部件Bar。它带有两个参数:

  • height条形的相对值(0.0和之间的值1.0)
  • label下面显示的文字

然后我们定义两个常量:

  • _baseDurationMs一个高度条1.0进行动画处理的时间
  • _maxElementHeight 具有高度的条形的像素值 1.0

看起来像这样:

class Bar extends StatelessWidget {
 final double height;
 final String label;

 final int _baseDurationMs = 1000;
 final double _maxElementHeight = 100;

 Bar(this.height, this.label);

 @override
 Widget build(BuildContext context) {
 // TODO
 }
}

现在我们可以编写渲染函数。它返回一个ControlledAnimation来自“ 简单动画包”https://pub.dev/packages/simple_animations的窗口小部件。它可以简单地从动画开始。它包含三个参数:

  • duration(在这里我们乘height用_baseDurationMs得到的所有条形图速度相同)
  • tween(从动画中的值0.0,以我们的height)
  • builder函数,可在每个动画步骤中渲染条形(我们将“当前动画值”作为第二个参数传入)

对于此演示,使用了非常简单的布局。这是一列带有“empty space”-container的列,其后是“blue-colored container”和标签。

看一看:

class Bar extends StatelessWidget {
 // ...

 @override
 Widget build(BuildContext context) {
 return ControlledAnimation(
 duration: Duration(milliseconds: (height * _baseDurationMs).round()),
 tween: Tween(begin: 0.0, end: height),
 builder: (context, animatedHeight) {
 return Column(
 children: [
 Container(
 height: (1 - animatedHeight) * _maxElementHeight,
 ),
 Container(
 width: 20,
 height: animatedHeight * _maxElementHeight,
 color: Colors.blue,
 ),
 Text(label)
 ],
 );
 },
 );
 }
}

我们有一个动画Bar。现在,我们可以通过将一些Bar小部件放在一行中来完成此示例:

class BarChartApplication extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 return Padding(
 padding: const EdgeInsets.all(20.0),
 child: Row(
 mainAxisAlignment: MainAxisAlignment.spaceEvenly,
 children: [
 Bar(0.3, "2013"),
 Bar(0.5, "2014"),
 Bar(0.7, "2015"),
 Bar(0.8, "2016"),
 Bar(0.9, "2017"),
 Bar(0.98, "2018"),
 Bar(0.84, "2019"),
 ],
 ),
 );
 }
}

现在,我们有了这个动画效果很好的条形图。(当然,您可以改善条形图的外观。我希望此示例保持简单。)


完整的演示可在此处获得代码(https://github.com/felixblaschke/simple_animations_example_app/blob/master/lib/examples/bar_chart.dart)。随时克隆“简单动画示例(https://github.com/felixblaschke/simple_animations_example_app/blob/master/lib/examples/bar_chart.dart)并试用使用该第三方软件包创建的一些很棒的演示。

翻译自:https://medium.com/@felixblaschke/animated-bar-chart-in-flutter-9bcd56e163aa

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表