Example of using AnimatedContainer in Flutter

Last updated on November 12, 2020 A Goodman Loading... Post a comment

The AnimatedContainer widget is used to make simple animations in Flutter.

Notes:

  • The properties that are null are not animated.
  • AnimatedContainer’s child and descendants are not animated.

Below is an example of using the AnimatedContainer widget.

Screen record at the end:

Full code:

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

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

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

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

class _HomePageState extends State<HomePage> {
  double _width = 100; // the width at the beginning
  double _height = 100; // the height at the beginning
  Color _color = Colors.yellow; // the color at the beginning

  void _start() {
    setState(() {
      _width = 300;
      _height = 300;
      _color = Colors.red;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        color: Colors.black87,
        child: AnimatedContainer(
          duration: Duration(seconds: 2),
          width: _width,
          height: _height,
          decoration: BoxDecoration(shape: BoxShape.circle, color: _color),
          curve: Curves.decelerate,
          onEnd: () {
            setState(() {
              _width = _width == 100 ? 300 : 100;
              _height = _height == 100 ? 300 : 100;
              _color = _color == Colors.yellow ? Colors.red : Colors.yellow;
            });
          },
        ),
      ),
      floatingActionButton: ElevatedButton.icon(
          onPressed: _start,
          icon: Icon(Icons.run_circle),
          label: Text('Start Infinite Pulsating')),
    );
  }
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles