Flutter,如何在没有按钮触发的情况下自动制作动画

Flutter, how to automatically animate without a button trigger

我有一些动画代码可以无限改变背景颜色

但问题是我想在没有按钮触发器的情况下执行此操作

我希望它在第一次(第一次加载时)自动运行

下面是代码

我很困,谁能帮忙

目的是在没有触发器的情况下制作动画,它会自动运行改变背景的动画

import 'package:flutter/material.dart';

class ScreenTime extends StatefulWidget {
 @override
_ScreenTimeState createState() => _ScreenTimeState();
}

class _ScreenTimeState extends State<ScreenTime> {
  List<Color> colorList = [
  Colors.red,
  Colors.blue,
  Colors.green,
  Colors.yellow
 ];
List<Alignment> alignmentList = [
  Alignment.bottomLeft,
  Alignment.bottomRight,
  Alignment.topRight,
  Alignment.topLeft,
];
 int index = 0;
 Color bottomColor = Colors.black54;
 Color topColor = Colors.white10;
 Alignment begin = Alignment.bottomLeft;
 Alignment end = Alignment.topRight;


@override
Widget build(BuildContext context) {

return Scaffold(
    body: Stack(
      children: [
        AnimatedContainer(
          duration: Duration(seconds: 2),
          onEnd: () {
            setState(() {
              index = index + 1;
              // animate the color
              bottomColor = colorList[index % colorList.length];
              topColor = colorList[(index + 1) % colorList.length];

              //// animate the alignment
              // begin = alignmentList[index % alignmentList.length];
              // end = alignmentList[(index + 2) % alignmentList.length];
            });
          },
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  begin: begin, end: end, colors: [bottomColor, topColor])),
        ),
        Positioned.fill(
          child: IconButton(
            icon: Icon(Icons.play_arrow),
            onPressed: () {
              setState(() {
                bottomColor = Colors.blue;
              });
            },
          ),
        )
      ],
    ));
 }
}

这个问题的目的基本上是“如何在没有触发器的情况下为 AnimatedContainer 设置动画”

我想我找到了解决方案

我做的是

只需创建一个新函数,然后在构建方法中调用该方法

方法代码如下

 setState(() {
  index = index + 1;
  bottomColor = Colors.blue;
});

我的第二个解决方案是这个,我认为它有效

但我担心它是否有任何副作用

WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));

为了在解决问题的同时尽可能多地保留原始实现,请执行

WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {bottomColor = Colors.blue;}));

in initState 不会造成问题。这只要在 initState 中完成即可。在 build 中调用它会导致不需要的额外无限循环。

但是,在 repeat 上使用 AnimationController 几乎可以肯定是更简洁的实现。