FlyingOddo
FlyingOddo

Reputation: 55

Flutter LinearGradient Animation for Draggable

I have a Draggable Container with the following decoration.

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

I would like to have it animated that my frame is getting greener or redder, further I drag left or right.

Upvotes: 2

Views: 1351

Answers (1)

Mariano Zorrilla
Mariano Zorrilla

Reputation: 7686

Here's a simple example to detect horizontal drag and change between colors inside your gradient:

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

The result of this easy implementation is the following:


Gradient Drag Effect

Upvotes: 3

Related Questions