[Flutter] Cookbook - Animate the properties of a container

jaehee kim·2021년 6월 5일
1

Flutter

목록 보기
6/20
post-thumbnail

Animate the properties of a container

Animation을 이용하여 Container의 모양, 색상, 크기가 변화하도록 하는 방법에 대해서 알아보겠습니다.

이러한 Animation을 위해서 Flutter에서 제공하는 AnimatedContainer 를 사용하겠습니다. AnimatedContainer는 rebuild하면 이전 값에서 새로운 값으로 property가 변경되면서 animation이 작동하고, Flutter에서는 이를 implicit animations 이라고 합니다.

Create a StatefulWidget with default properties

class AnimatedContainerApp extends StatefulWidget {
  
  _AnimatedContainerAppState createState() => _AnimatedContainerAppState();
}

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

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('AnimatedContainer Demo'),
        ),
        body: Center(),
      ),
    );
  }
}

Build an AnimatedContainer using the properties

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: Duration(seconds: 1),
  // Provide an optional curve to make the animation feel smoother.
  curve: Curves.fastOutSlowIn,
)

Start the animation by rebuilding with new properties

setState() 를 호출하여 새로운 값으로 property를 업데이트 합니다.

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: Icon(Icons.play_arrow),
)

Example







Reference

[Cookbook - Animate the properties of a container]

0개의 댓글