Flutter - #26. AnimatedContainer

Pearl Lee·2021년 6월 29일
0

Flutter Widget

목록 보기
25/50

내가 보려고 쓰는 Flutter 일기
참고1 : https://api.flutter.dev/flutter/widgets/AnimatedContainer-class.html
참고2 : Do it! 플러터 앱 프로그래밍, 조준수 [이지스퍼블리싱]








AnimatedContainer

오늘 배워볼 것은 AnimatedContainer.
Animated 버전의 Container라고 한다. Container인데 애니메이션 효과가 추가된 컨테이너! 정도이다.
정해둔 시간(duration)동안 curve에 설정한 애니메이션 효과가 발생하며 설정한 값(width, height 등)으로 위젯이 변한다.

curve에 설정할 수 있는 속성들은 flutter.dev에 가면 설명이 나와있다. 내가 보는 플러터 책에 해당 사이트를 소개해두었더라. Curves class
좋은 책이야..

플러터가 제공하는 애니메이션은 선형보간법을 활용한다고 한다. 위키백과에 찾았더니 요렇게 나왔다.

선형 보간법(線型補間法, linear interpolation)은 끝점의 값이 주어졌을 때 그 사이에 위치한 값을 추정하기 위하여 직선 거리에 따라 선형적으로 계산하는 방법이다. 위키백과-선형보간법

그냥 Curves class 에서 마음에 드는 거 쓰도록 하자.









코드 예시로 알아보자

오늘도 공식 페이지의 코드를 가져다 이리저리 돌려보자.


import 'package:flutter/material.dart';

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

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);


  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Code Sample',
      home: Scaffold(
        appBar: AppBar(title: const Text('Test AnimatedContainer')),
        body: const MyStatefulWidget(),
      ),
    );
  }
}

/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool selected = false;

  
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          selected = !selected;
        });
      },
      child: Center(
        child: AnimatedContainer(
          width: selected ? 300.0 : 150.0,
          height: selected ? 100.0 : 300.0,
          color: selected ? Colors.red : Colors.blue,
          alignment:
          selected ? Alignment.centerLeft : AlignmentDirectional.topCenter,
          duration: const Duration(seconds: 2),
          curve: Curves.fastOutSlowIn,
          child: const FlutterLogo(size: 75),
        ),
      ),
    );
  }
}

AnimatedContainer를 GestureDetector로 감싸서, 터치 이벤트 등에 반응하도록 해주었다. onTap (클릭) 이벤트가 발생하면, selected 값을 바꿔 AnimatedContainer위젯을 변화시킨다.
alignment는 container 내부 child요소 (여기서는 플러터 로고)의 컨테이너 내 위치를 결정한다. 2초 동안 실행되고, curve는 마음대로 주면 된다.
curve를 바꿔서 실행 결과를 보자.

Curves.fastOutSlowInCurves.bounceInOutCurves.elasticIn

그냥 깔끔하게 변하는 linear나 easeIn 같은 게 나은 듯;;







오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글