Container 类提供了一种便捷的方法来创建具有特定属性的 widget:宽度、高度、背景颜色、内边距、边框等。

简单的动画通常涉及随时间更改这些属性。例如,你可能希望将背景颜色从灰色动画到绿色,以指示用户已选择某个项目。

为了对这些属性添加动画效果,Flutter 提供了 AnimatedContainer widget。与 Container widget 一样,AnimatedContainer 允许你定义宽度、高度、背景颜色等。但是,当 AnimatedContainer 使用新属性重新构建时,它会自动在新旧值之间进行动画。在 Flutter 中,这类动画被称为“隐式动画”。

本教程描述了如何使用 AnimatedContainer 在用户点击按钮时,通过以下步骤为大小、背景颜色和边框半径添加动画效果

  1. 使用默认属性创建 StatefulWidget。
  2. 使用属性构建 AnimatedContainer
  3. 通过使用新属性重新构建来启动动画。

1. 使用默认属性创建 StatefulWidget

#

首先,创建 StatefulWidgetState 类。使用自定义的 State 类定义随时间变化的属性。在本示例中,这包括宽度、高度、颜色和边框半径。你还可以定义每个属性的默认值。

这些属性属于自定义的 State 类,因此当用户点击按钮时可以更新它们。

dart
class AnimatedContainerApp extends StatefulWidget {
  const AnimatedContainerApp({super.key});

  @override
  State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();
}

class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
  // Define the various properties with default values. Update these properties
  // when the user taps a FloatingActionButton.
  double _width = 50;
  double _height = 50;
  Color _color = Colors.green;
  BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);

  @override
  Widget build(BuildContext context) {
    // Fill this out in the next steps.
  }
}

2. 使用属性构建 AnimatedContainer

#

接下来,使用上一步中定义的属性构建 AnimatedContainer。此外,提供一个 duration 来定义动画应运行多长时间。

dart
AnimatedContainer(
  // Use the properties stored in the State class.
  width: _width,
  height: _height,
  decoration: BoxDecoration(
    color: _color,
    borderRadius: _borderRadius,
  ),
  // Define how long the animation should take.
  duration: const Duration(seconds: 1),
  // Provide an optional curve to make the animation feel smoother.
  curve: Curves.fastOutSlowIn,
)

3. 通过使用新属性重新构建来启动动画

#

最后,通过使用新属性重新构建 AnimatedContainer 来启动动画。如何触发重新构建?使用 setState() 方法。

向应用添加一个按钮。当用户点击按钮时,在对 setState() 的调用中,使用新的宽度、高度、背景颜色和边框半径更新属性。

实际应用通常在固定值之间转换(例如,从灰色背景到绿色背景)。对于本应用,每次用户点击按钮时都会生成新值。

dart
FloatingActionButton(
  // When the user taps the button
  onPressed: () {
    // Use setState to rebuild the widget with new values.
    setState(() {
      // Create a random number generator.
      final random = Random();

      // Generate a random width and height.
      _width = random.nextInt(300).toDouble();
      _height = random.nextInt(300).toDouble();

      // Generate a random color.
      _color = Color.fromRGBO(
        random.nextInt(256),
        random.nextInt(256),
        random.nextInt(256),
        1,
      );

      // Generate a random border radius.
      _borderRadius = BorderRadius.circular(
        random.nextInt(100).toDouble(),
      );
    });
  },
  child: const Icon(Icons.play_arrow),
)

互动示例

#
import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(const AnimatedContainerApp());

class AnimatedContainerApp extends StatefulWidget {
  const AnimatedContainerApp({super.key});

  @override
  State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();
}

class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
  // Define the various properties with default values. Update these properties
  // when the user taps a FloatingActionButton.
  double _width = 50;
  double _height = 50;
  Color _color = Colors.green;
  BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('AnimatedContainer Demo')),
        body: Center(
          child: AnimatedContainer(
            // Use the properties stored in the State class.
            width: _width,
            height: _height,
            decoration: BoxDecoration(
              color: _color,
              borderRadius: _borderRadius,
            ),
            // Define how long the animation should take.
            duration: const Duration(seconds: 1),
            // Provide an optional curve to make the animation feel smoother.
            curve: Curves.fastOutSlowIn,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          // When the user taps the button
          onPressed: () {
            // Use setState to rebuild the widget with new values.
            setState(() {
              // Create a random number generator.
              final random = Random();

              // Generate a random width and height.
              _width = random.nextInt(300).toDouble();
              _height = random.nextInt(300).toDouble();

              // Generate a random color.
              _color = Color.fromRGBO(
                random.nextInt(256),
                random.nextInt(256),
                random.nextInt(256),
                1,
              );

              // Generate a random border radius.
              _borderRadius = BorderRadius.circular(
                random.nextInt(100).toDouble(),
              );
            });
          },
          child: const Icon(Icons.play_arrow),
        ),
      ),
    );
  }
}