Flutter: ColorTween Example

Last updated on September 10, 2021 A Goodman Loading... Post a comment

A short example of using ColorTween in Flutter.

App Preview

The complete code:

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Color?> _color;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(seconds: 5),
      vsync: this,
    )..repeat(reverse: true);

    _color =
        ColorTween(begin: Colors.blue, end: Colors.amber).animate(_controller);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        color: Colors.black87,
        child: AnimatedBuilder(
          animation: _color,
          builder: (BuildContext _, Widget? __) {
            return Container(
              width: 300,
              height: 300,
              decoration:
                  BoxDecoration(color: _color.value, shape: BoxShape.circle),
            );
          },
        ),
      ),
    );
  }
}

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles