【问题标题】:Flutter, how to automatically animate without a button triggerFlutter,如何在没有按钮触发的情况下自动制作动画
【发布时间】:2020-08-22 02:20:30
【问题描述】:

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

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

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

下面是代码

我被困住了,谁能帮忙

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

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;
              });
            },
          ),
        )
      ],
    ));
 }
}

【问题讨论】:

    标签: flutter flutter-layout flutter-animation


    【解决方案1】:

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

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

    initState 不会造成问题。只要在initState 中完成即可。在build 中调用它会导致一个不受欢迎的额外无限循环。

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

    【讨论】:

      【解决方案2】:

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

      我想我找到了解决办法

      我做的是

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

      方法代码如下

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

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

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

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

      【讨论】:

      • 这不是一个解决方案,它只有在按 ctrl + s 时才有效
      • 这确实应该作为对您的问题帖子的编辑。这是您解决问题的尝试,这很好,但由于它并不能真正回答您的问题,因此不应该这样发布。
      猜你喜欢
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 2017-07-13
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      相关资源
      最近更新 更多