如何在抖动中缩小和增长图标动画?

时间:2020-04-21 07:02:45

标签: flutter flutter-layout flutter-animation flutter-widget

我正在使用以下代码对图标执行动画放大和缩小动画,但是为此,我必须单击该图标,我们希望动画在屏幕上重复出现。

Serializable

我希望输出如下图所示,其中外部部分不断增长和收缩。

enter image description here

1 个答案:

答案 0 :(得分:3)

您可以使用多种方法来解决此问题。我最好使用重复播放动画的AnimationController。

animationController = AnimationController(
  vsync: this,
  duration: Duration(seconds: 1),
)
  ..forward()
  ..repeat(reverse: true);

例如,您可以为按钮周围的填充动画大小。我会在IconButton周围使用圆形容器。

为此,您需要在状态中初始化AnimationController。记住要在小部件的生命周期结束时进行处理。

以下是Codepen和dartpad上的示例:

enter image description here

https://codepen.io/orestesgaolin/pen/MWajRGV

https://dartpad.dartlang.org/ca4838f17ea6061cf0212a4b689eaf2a

完整的源代码可以在该要点中找到

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Animated Icon',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: Duration(seconds: 1),
    )
      ..forward()
      ..repeat(reverse: true);
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.blue,
        child: Center(
          child: AnimatedBuilder(
            animation: animationController,
            builder: (context, child) {
              return Container(
                decoration: ShapeDecoration(
                  color: Colors.white.withOpacity(0.5),
                  shape: CircleBorder(),
                ),
                child: Padding(
                  padding: EdgeInsets.all(8.0 * animationController.value),
                  child: child,
                ),
              );
            },
            child: Container(
              decoration: ShapeDecoration(
                color: Colors.white,
                shape: CircleBorder(),
              ),
              child: IconButton(
                onPressed: () {},
                color: Colors.blue,
                icon: Icon(Icons.calendar_today, size: 24),
              ),
            ),
          ),

        ),
      ),
    );
  }
}