Flutter DecoratedBoxTransition example

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

In general, the DecoratedBoxTransition widget usually goes with the following widgets/classes:

  • AnimationController
  • DecorationTween
  • BoxDecoration

Below is a complete example of using the DecoratedBoxTransition widget in a Flutter application.

Example

Preview:

The full code:

// main.dart
import 'package:flutter/material.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;

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

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

  final DecorationTween _decorationTween = DecorationTween(
      begin: BoxDecoration(
          color: Colors.yellow,
          shape: BoxShape.circle,
          boxShadow: [
            BoxShadow(offset: Offset(0, 0), blurRadius: 30, spreadRadius: 0)
          ],
          border: Border.all(width: 10, color: Colors.orange)),
      end: BoxDecoration(
          color: Colors.purple,
          shape: BoxShape.circle,
          boxShadow: [
            BoxShadow(offset: Offset(20, 20), blurRadius: 30, spreadRadius: 0)
          ],
          border: Border.all(width: 50, color: Colors.red)));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: DecoratedBoxTransition(
          decoration: _decorationTween.animate(_controller),
          child: Container(
            width: 250,
            height: 250,
          ),
        ),
      ),
    );
  }
}

Note: To be able to use vsync: this, the private State class needs to go with the TickerProviderStateMixin class.

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