如何在flutter中连续改变背景

nou*_*ace 9 flutter

我知道如何改变背景,但我需要它不断变化。

我如何实现这一目标?

Ser*_*rte 20

您可以使用 anAnimatedContainer并在动画结束时重置目标颜色。为了平滑过渡,我建议您可以循环使用颜色列表,您可以对对齐进行相同的操作。

例子:

在此处输入图片说明

示例的源代码:

import 'package:flutter/material.dart';

class AnimatedGradient extends StatefulWidget {
  @override
  _AnimatedGradientState createState() => _AnimatedGradientState();
}

class _AnimatedGradientState extends State<AnimatedGradient> {
  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.red;
  Color topColor = Colors.yellow;
  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;
              });
            },
          ),
        )
      ],
    ));
  }
}

Run Code Online (Sandbox Code Playgroud)

  • 你好,但是如果要自动设置动画怎么办?此代码有一个触发按钮 (4认同)
  • 你可以只使用初始化状态@nounlace (3认同)

小智 6

要自动设置渐变动画,只需在SeriForte 的代码@override Widget build(BuildContext context) {}方法中添加此代码块即可

Future.delayed(const Duration(milliseconds: 10), () {
  setState(() {
    bottomColor = Colors.blue;
  });
});
Run Code Online (Sandbox Code Playgroud)