13.2 C
New York
Saturday, April 1, 2023

Flutter DecoratedBoxTransition example

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.Advertisements

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.

Advertisements

Related Articles

Latest Articles