使用多个图像创建链式颤动动画

Create chained flutter animation with multiple images

我想创建一个带有动画的小部件,该动画由显示一系列图像淡入淡出并在完成后重复播放组成。像这个附加动画:

由于我是 Flutter 的新手,我想知道最好的方法是什么。

您可以使用 AnimationController. After setup animation controller, you just call the repeat function. The animation will be going to a limitless loop. With AnimationStatusListener 您可以更改颜色和标题文本。

这可以通过 AnimatedSwitcher 小部件来完成。它是 Flutter 易于使用的隐式动画小部件之一。它的主要工作是在其子部件更改时自动创建交叉淡入淡出过渡。

您可以通过更改下面的字符串并进行热重载来查看它的运行情况。您将看到 200 毫秒的淡入淡出过渡:

AnimatedSwitcher(
  duration: Duration(milliseconds: 200),
  child: Text(
    'Hello', // manually change the text here, and hot reload
    key: UniqueKey(),
  ),
)

一旦您理解了 AnimatedSwitcher 的工作原理,您就可以决定如何遍历列表图像。为了简单起见,我给你一个使用文本的例子,但想法是一样的。

完整源代码:

import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  late final Timer timer;

  final values = ['A', 'B', 'C', 'D'];
  int _index = 0;

  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() => _index++);
    });
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo'),
      ),
      body: Center(
        child: AnimatedSwitcher(
          duration: Duration(milliseconds: 200),
          child: Text(
            values[_index % values.length],
            key: UniqueKey(),
          ),
        ),
      ),
    );
  }
}