Creating an Animated Gradient Background in Flutter

Learn how to create an animated gradient background in Flutter using the AnimatedContainer widget and the Timer class.

In this tutorial, we will show you how to create an animated gradient background in Flutter using the AnimatedContainer widget and the Timer class. We will start by creating a GradientBackground widget that will hold the animated gradient background. We will then use the Timer class to change the background colors at a fixed interval. Finally, we will use the AnimatedContainer widget to animate the color transition.


Usage:

To use the GradientBackground widget, simply add it to your Flutter app as a child of any other widget that needs a gradient background.

Code:

import 'dart:async';
import 'package:flutter/material.dart';

class GradientBackground extends StatefulWidget {
  const GradientBackground({Key? key}) : super(key: key);

  @override
  GradientBackgroundState createState() => GradientBackgroundState();
}

class GradientBackgroundState extends State {
  final List _colors = [
    const Color(0xFFEECDA3),
    const Color(0xFFEF629F),
  ];

  int _currentColorIndex = 0;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _startTimer();
  }

  // Start the timer
  void _startTimer() {
    // Set up a periodic timer that triggers the color change every 3 seconds
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      setState(() {
        _currentColorIndex = (_currentColorIndex + 1) % _colors.length;
      });
    });
  }

  // Cancel the timer when the widget is disposed
  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: const Duration(seconds: 1),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            _colors[_currentColorIndex], // Use the current color
            _colors[(_currentColorIndex + 1) % _colors.length], // Use the next color in the list
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
      ),
    );
  }
}

..


Properties:

  • GradientBackground: A widget that creates an animated gradient background.
  • _colors: A list of colors used for the gradient background.
  • _currentColorIndex: An integer representing the current color index in the _colors list.
  • _timer: A timer that triggers the color change at a fixed interval.
  • _startTimer(): A method that starts the timer.
  • dispose(): A method that cancels the timer when the widget is disposed.
  • build(): A method that builds the widget tree and returns an AnimatedContainer with a gradient background that transitions between two colors.
..
Flutter,


Comments