首页 > 解决方案 > 可拖动的 Flutter LinearGradient 动画

问题描述

我有一个带有以下装饰的可拖动容器。

  decoration: BoxDecoration(
      gradient: LinearGradient(
          colors: [ThemeColors.red, ThemeColors.yellow, ThemeColors.green])

我想让它动画我的框架变得更绿或更红,进一步向左或向右拖动。

标签: animationflutterdart

解决方案


这是一个简单的示例,用于检测渐变内颜色之间的水平拖动和变化:

class GradientScreen extends StatefulWidget {
  @override
  _GradientScreenState createState() => _GradientScreenState();
}

class _GradientScreenState extends State<GradientScreen> {

  var percentage = 0.0;

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        title: Text('Animated Drag Gradient'),
        centerTitle: true,
      ),
      body: GestureDetector(
        onHorizontalDragUpdate: (details) {
          setState(() => percentage = (details.localPosition.dx - 0) / (width - 0));
        },
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                _colorTween(Colors.green[900], Colors.red[900]),
                Colors.yellow,
                _colorTween(Colors.green[900], Colors.red[900])
              ],
            )
          ),
        ),
      ),
    );
  }

  Color _colorTween(Color begin, Color end) {
    return ColorTween(begin: begin, end: end).transform(percentage);
  }
}

这种简单实现的结果如下:


渐变拖曳效果


推荐阅读