Overview.
AnimatedWidget 구현체 들과 AnimationController , Animation 에 대해 알아보자
- AnimatedWidget
- AnimationController
- Animation
- AnimatedWidget - ScaleTransition
- AnimatedWidget - FadeTrasition
- AnimatedWidget - RotatedTransition
- AnimationWidget - PositionedTransition
0. 문서
https://api.flutter.dev/flutter/widgets/AnimatedWidget-class.html
AnimatedWidget class - widgets library - Dart API
A widget that rebuilds when the given Listenable changes value. AnimatedWidget is most commonly used with Animation objects, which are Listenable, but it can be used with any Listenable, including ChangeNotifier and ValueNotifier. AnimatedWidget is most us
api.flutter.dev
https://docs.flutter.dev/ui/animations/tutorial
Animations tutorial
A tutorial showing how to build explicit animations in Flutter.
docs.flutter.dev
https://api.flutter.dev/flutter/widgets/PositionedTransition-class.html
PositionedTransition class - widgets library - Dart API
Animated version of Positioned which takes a specific Animation to transition the child's position from a start position to an end position over the lifetime of the animation. Only works if it's the child of a Stack. Here's an illustration of the Positione
api.flutter.dev
https://api.flutter.dev/flutter/widgets/RotationTransition-class.html
RotationTransition class - widgets library - Dart API
Animates the rotation of a widget. Here's an illustration of the RotationTransition widget, with it's turns animated by a CurvedAnimation set to Curves.elasticOut: link To create a local project with this code sample, run: flutter create --sample=widgets.R
api.flutter.dev
https://api.flutter.dev/flutter/widgets/ScaleTransition-class.html
ScaleTransition class - widgets library - Dart API
Animates the scale of a transformed widget. Here's an illustration of the ScaleTransition widget, with it's scale animated by a CurvedAnimation set to Curves.fastOutSlowIn: The following code implements the ScaleTransition as seen in the video above: link
api.flutter.dev
https://api.flutter.dev/flutter/widgets/FadeTransition-class.html
FadeTransition class - widgets library - Dart API
Animates the opacity of a widget. For a widget that automatically animates between the sizes of two children, fading between them, see AnimatedCrossFade. Here's an illustration of the FadeTransition widget, with it's opacity animated by a CurvedAnimation s
api.flutter.dev
1. AnimatedWidget
추상클래스 AnimatedWidget 에는 다양한 구현체가 있습니다.
AlignTransition , DecoratedBoxTransition , DefaultTextStyleTransition ... , PositionedTransition , SlideTransition .. 등등
그 중 저희는 그 전에 AnimationController 에 대해 알아보고 ScaleTransition 을 구현해보도록 하겠습니다.
2. AnimationController
AnimationController 는 말 그대로 애니메이션을 어떤식으로 할 것인지를 정할 수 있는데요.
forward , repeat 등등 다양한 컨트롤이 가능합니다.
애니메이션을 만들때는 이 컨트롤러를 사용하기 때문에 집고 넘어가도록 하겠습니다.
[ 공식 문서와 약간의 차이가 있습니다. 간단하게 만들었기 때문.. ]
먼저 StatefulWidget 을 설정을 하고 State<_Home> 옆에 with 를 사용하여 SingleTickerProviderStateMixin 또는 TickerProviderStateMixin 를 가져옵니다.
class _Home extends StatefulWidget {
const _Home({super.key});
@override
State<_Home> createState() => _HomeState();
}
class _HomeState extends State<_Home> with SingleTickerProviderStateMixin
참조!!
with는 여러 개의 부모 클래스를 가질 수 있으며, 각 메소드를 일일이 구현하지 않더라도 부모에서 구현된 메소드 호출을 할 수 있습니다.
_HomeState 클래스에 전역 변수로 AnimationController 를 정의하는데 이때 저는 late 키워드를 사용하였습니다.
late 키워드는 나중에 초기화가 될 것이라는 것을 컴파일러에게 알립니다.
class _HomeState extends State<_Home> with SingleTickerProviderStateMixin {
// AnimationController 타입
// late 나중에 값을 할당할 것임을 나타냄
late AnimationController _animationController;
@override 를 통해 iniState [제일 먼저 실행] 와 dispose[애니메이션 삭제] 를 오버라이드 한 후
initState 에서는 AnimationController 의 초기화를 dispose 에서는 애니메이션 삭제를 준비합니다.
// 초기화
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: Duration(seconds: 3),
vsync: this
);
}
// 애니메이션 효과 제외시키기
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
이때 잠깐!!
AnimationController 의 반드시 생성자에 넣어야 할 것이 두 개가 있는데 duration 과 vsync 입니다.
duration 에는 몇초동안 실행 될 것인지 , vsync 는 SingleTickerProviderStateMixin 을 상속한 자기 자신을 넣어 줍니다.
AnimationController 의 dispose 메서드를 사용하여 효과를 제거 시킬 수 도 있습니다.
AnimationController 를 실행 시키기 위해서는 AnimationController 의 메서드를 호출해야하는데 repeat , forward 등등이 있습니다. 이를 저는 initState 함수에 넣겠습니다.
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: Duration(seconds: 3),
vsync: this
);
// 애니메이션 동작 시키기
_animationController.repeat();
}
3. Animation
이제 거의 끝났습니다.
Animation 이라는 추상 클래스가 있는데요 이를 구현해야하기 때문에 Tween 클래스의 animate 메서드를 사용하겠습니다.
animate 안에는 위에서 만들었던 AnimationController 를 넣어주면 Animation 추상클래스 구현이 완성되었습니다.
// 거의 공식
Animation<double> _animation=
Tween(begin: 0.0, end: 1.0).animate(
_animationController
);
완성된 Animation 코드
class _HomeState extends State<_Home> with SingleTickerProviderStateMixin {
// AnimationController 타입
// late 나중에 값을 할당할 것임을 나타냄
late AnimationController _animationController;
// 초기화
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: Duration(seconds: 3),
vsync: this
);
// 애니메이션 동작 시키기
_animationController.repeat();
}
// 애니메이션 효과 제외시키기
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// 거의 공식
Animation<double> _animation=
Tween(begin: 0.0, end: 1.0).animate(
_animationController
);
return // 이제 마음껏 할 수 있음 ;
}
}
4. AnimationWidget - ScaleTransition
ScaleTransition 은 AnimateWidget 을 구현한 구현체 중 하나입니다.
[뭐 부모에 MatrixTransition 을 상속받기도 하였습니다.]
사실 이제 거의 끝난게 scale 에다가 위의 Animation 를 넣어 주기만 하면 되요 ㅎㅎ..
ScaleTransition(
scale: _animation,
child: Container(
width: 200,
height: 200,
color: Colors.blue,
),
)
이제 해당 위에 코드를 돌려 봅시다. [dispose 는 사용하지 않았습니다. 알아서 홧팅]
5. AnimationWidget - FadeTransition
FadeTransition 또한 별거 없습니다.
FadeTransition buildFadeTransition(Animation<double> _animation) {
return FadeTransition(
opacity: _animation,
child: Container(
width: 200,
height: 200,
color: Colors.blue,
),
);
}
6. AnimationWidget - RotationTransition
Rotation 즉, 돌아간 드아아ㅏㅇ 입니다.
위와 동일합니다.
RotationTransition(
turns : _animation,
child: Container(
width: 200,
height: 200,
color: Colors.blue,
),
)
7. AnimationWidget - PositionedTransition
얘는 좀 힘든데 공식 문서를 참조하여 만들었습니다.
Positioned 즉, 위치를 변경할 수 있는 녀석입니다.
Stack 안에서 동작할 수 있습니다.
공식 문서에서는 LayoutBuilder 를 사용하였네요!!
또한 LayoutBuilder 의 builder 를 사용하여 Stack 을 만듭니다.
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final Size biggest = constraints.biggest; // 위치
// Stack 안에 있어야함
return Stack(
children: <Widget>[]
),
해당 PositionedTransition 은 다음과 같습니다. rect 와 child 가 required 이므로 넣어 주어야 겠죵
PositionedTransition(
rect: RelativeRectTween(
// fromSize : 사이즈 줄이기 키우기
// fromLTWH : 위치 바꾸기
begin: RelativeRect.fromLTRB(
0, 0, smallLogo, smallLogo,
),
end: RelativeRect.fromSize(
Rect.fromLTWH(biggest.width - bigLogo,
biggest.height - bigLogo, bigLogo, bigLogo),
biggest,
),
).animate(CurvedAnimation(
parent: _animation,
curve: Curves.elasticInOut,
),
),
child: Image.asset('assets/image.jpeg'),
)
천천히 봅시다.
RelativeRectTween 입니다. begin , end 즉 처음 시작 위치와 종료 위치를 지정할 수 있습니다.
Tween 을 상속 받고 있으며 begin 과 end 에는 RelativeRect 클래스 의 fromSize 또는 fromLTRB를 지정하여 사용할 수 있습니다. 또한 fromRect , fromDirectional 다양하게 생성이 가능하네요.
// fromSize : 사이즈
// fromLTWH : 위치 바꾸기
begin: RelativeRect.fromLTRB(
0, 0, smallLogo, smallLogo,
),
end: RelativeRect.fromSize(
Rect.fromLTWH(biggest.width - bigLogo,
biggest.height - bigLogo, bigLogo, bigLogo),
biggest,
),
RelativeRectTween 함수중 animate 라는 함수가 있는데 이는 _AnimatedEvalution 즉 Animation 구현체를 리턴합니다.
Animation<T> animate(Animation<double> parent) {
return _AnimatedEvaluation<T>(parent, this);
}
이제 parent 에는 저희의 Animation를 넣으면 되겠네요!!
RelativeRectTween().animate(_animation),
물론 예제의 CurvedAnimation 을 사용하셔도 무방합니다. [물론 컨트롤러를 그냥 좀 바꿔야 되겠지만 ㅎㅎ 귀찮으니 패스]
RelativeRectTween().animate(CurvedAnimation(
parent: _animationController,
curve: Curves.elasticInOut,
),
child 에는 움직일 이미지나 등등 아무 Widget 을 넣도록 되어있네요.
child: Image.asset('assets/image.jpeg')
해당 PositionedAnimation 의 동영상입니다.
'flutter & dart' 카테고리의 다른 글
flutter & dart - AnimatedSwicher , AnimatedOpacity , AnimatedDefaultTextStyle (0) | 2024.04.03 |
---|---|
flutter & dart - AnimatedContainer (0) | 2024.04.03 |
flutter & dart - TabBar , DefaultTabController (0) | 2024.04.02 |
flutter & dart - Key (중요) , 이니셜라이저를 사용하는 이유 (0) | 2024.04.02 |
flutter & dart - 아코디언 같은 ExpantionPanelList (0) | 2024.04.02 |
Overview.
AnimatedWidget 구현체 들과 AnimationController , Animation 에 대해 알아보자
- AnimatedWidget
- AnimationController
- Animation
- AnimatedWidget - ScaleTransition
- AnimatedWidget - FadeTrasition
- AnimatedWidget - RotatedTransition
- AnimationWidget - PositionedTransition
0. 문서
https://api.flutter.dev/flutter/widgets/AnimatedWidget-class.html
AnimatedWidget class - widgets library - Dart API
A widget that rebuilds when the given Listenable changes value. AnimatedWidget is most commonly used with Animation objects, which are Listenable, but it can be used with any Listenable, including ChangeNotifier and ValueNotifier. AnimatedWidget is most us
api.flutter.dev
https://docs.flutter.dev/ui/animations/tutorial
Animations tutorial
A tutorial showing how to build explicit animations in Flutter.
docs.flutter.dev
https://api.flutter.dev/flutter/widgets/PositionedTransition-class.html
PositionedTransition class - widgets library - Dart API
Animated version of Positioned which takes a specific Animation to transition the child's position from a start position to an end position over the lifetime of the animation. Only works if it's the child of a Stack. Here's an illustration of the Positione
api.flutter.dev
https://api.flutter.dev/flutter/widgets/RotationTransition-class.html
RotationTransition class - widgets library - Dart API
Animates the rotation of a widget. Here's an illustration of the RotationTransition widget, with it's turns animated by a CurvedAnimation set to Curves.elasticOut: link To create a local project with this code sample, run: flutter create --sample=widgets.R
api.flutter.dev
https://api.flutter.dev/flutter/widgets/ScaleTransition-class.html
ScaleTransition class - widgets library - Dart API
Animates the scale of a transformed widget. Here's an illustration of the ScaleTransition widget, with it's scale animated by a CurvedAnimation set to Curves.fastOutSlowIn: The following code implements the ScaleTransition as seen in the video above: link
api.flutter.dev
https://api.flutter.dev/flutter/widgets/FadeTransition-class.html
FadeTransition class - widgets library - Dart API
Animates the opacity of a widget. For a widget that automatically animates between the sizes of two children, fading between them, see AnimatedCrossFade. Here's an illustration of the FadeTransition widget, with it's opacity animated by a CurvedAnimation s
api.flutter.dev
1. AnimatedWidget
추상클래스 AnimatedWidget 에는 다양한 구현체가 있습니다.
AlignTransition , DecoratedBoxTransition , DefaultTextStyleTransition ... , PositionedTransition , SlideTransition .. 등등
그 중 저희는 그 전에 AnimationController 에 대해 알아보고 ScaleTransition 을 구현해보도록 하겠습니다.
2. AnimationController
AnimationController 는 말 그대로 애니메이션을 어떤식으로 할 것인지를 정할 수 있는데요.
forward , repeat 등등 다양한 컨트롤이 가능합니다.
애니메이션을 만들때는 이 컨트롤러를 사용하기 때문에 집고 넘어가도록 하겠습니다.
[ 공식 문서와 약간의 차이가 있습니다. 간단하게 만들었기 때문.. ]
먼저 StatefulWidget 을 설정을 하고 State<_Home> 옆에 with 를 사용하여 SingleTickerProviderStateMixin 또는 TickerProviderStateMixin 를 가져옵니다.
class _Home extends StatefulWidget {
const _Home({super.key});
@override
State<_Home> createState() => _HomeState();
}
class _HomeState extends State<_Home> with SingleTickerProviderStateMixin
참조!!
with는 여러 개의 부모 클래스를 가질 수 있으며, 각 메소드를 일일이 구현하지 않더라도 부모에서 구현된 메소드 호출을 할 수 있습니다.
_HomeState 클래스에 전역 변수로 AnimationController 를 정의하는데 이때 저는 late 키워드를 사용하였습니다.
late 키워드는 나중에 초기화가 될 것이라는 것을 컴파일러에게 알립니다.
class _HomeState extends State<_Home> with SingleTickerProviderStateMixin {
// AnimationController 타입
// late 나중에 값을 할당할 것임을 나타냄
late AnimationController _animationController;
@override 를 통해 iniState [제일 먼저 실행] 와 dispose[애니메이션 삭제] 를 오버라이드 한 후
initState 에서는 AnimationController 의 초기화를 dispose 에서는 애니메이션 삭제를 준비합니다.
// 초기화
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: Duration(seconds: 3),
vsync: this
);
}
// 애니메이션 효과 제외시키기
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
이때 잠깐!!
AnimationController 의 반드시 생성자에 넣어야 할 것이 두 개가 있는데 duration 과 vsync 입니다.
duration 에는 몇초동안 실행 될 것인지 , vsync 는 SingleTickerProviderStateMixin 을 상속한 자기 자신을 넣어 줍니다.
AnimationController 의 dispose 메서드를 사용하여 효과를 제거 시킬 수 도 있습니다.
AnimationController 를 실행 시키기 위해서는 AnimationController 의 메서드를 호출해야하는데 repeat , forward 등등이 있습니다. 이를 저는 initState 함수에 넣겠습니다.
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: Duration(seconds: 3),
vsync: this
);
// 애니메이션 동작 시키기
_animationController.repeat();
}
3. Animation
이제 거의 끝났습니다.
Animation 이라는 추상 클래스가 있는데요 이를 구현해야하기 때문에 Tween 클래스의 animate 메서드를 사용하겠습니다.
animate 안에는 위에서 만들었던 AnimationController 를 넣어주면 Animation 추상클래스 구현이 완성되었습니다.
// 거의 공식
Animation<double> _animation=
Tween(begin: 0.0, end: 1.0).animate(
_animationController
);
완성된 Animation 코드
class _HomeState extends State<_Home> with SingleTickerProviderStateMixin {
// AnimationController 타입
// late 나중에 값을 할당할 것임을 나타냄
late AnimationController _animationController;
// 초기화
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: Duration(seconds: 3),
vsync: this
);
// 애니메이션 동작 시키기
_animationController.repeat();
}
// 애니메이션 효과 제외시키기
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// 거의 공식
Animation<double> _animation=
Tween(begin: 0.0, end: 1.0).animate(
_animationController
);
return // 이제 마음껏 할 수 있음 ;
}
}
4. AnimationWidget - ScaleTransition
ScaleTransition 은 AnimateWidget 을 구현한 구현체 중 하나입니다.
[뭐 부모에 MatrixTransition 을 상속받기도 하였습니다.]
사실 이제 거의 끝난게 scale 에다가 위의 Animation 를 넣어 주기만 하면 되요 ㅎㅎ..
ScaleTransition(
scale: _animation,
child: Container(
width: 200,
height: 200,
color: Colors.blue,
),
)
이제 해당 위에 코드를 돌려 봅시다. [dispose 는 사용하지 않았습니다. 알아서 홧팅]
5. AnimationWidget - FadeTransition
FadeTransition 또한 별거 없습니다.
FadeTransition buildFadeTransition(Animation<double> _animation) {
return FadeTransition(
opacity: _animation,
child: Container(
width: 200,
height: 200,
color: Colors.blue,
),
);
}
6. AnimationWidget - RotationTransition
Rotation 즉, 돌아간 드아아ㅏㅇ 입니다.
위와 동일합니다.
RotationTransition(
turns : _animation,
child: Container(
width: 200,
height: 200,
color: Colors.blue,
),
)
7. AnimationWidget - PositionedTransition
얘는 좀 힘든데 공식 문서를 참조하여 만들었습니다.
Positioned 즉, 위치를 변경할 수 있는 녀석입니다.
Stack 안에서 동작할 수 있습니다.
공식 문서에서는 LayoutBuilder 를 사용하였네요!!
또한 LayoutBuilder 의 builder 를 사용하여 Stack 을 만듭니다.
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final Size biggest = constraints.biggest; // 위치
// Stack 안에 있어야함
return Stack(
children: <Widget>[]
),
해당 PositionedTransition 은 다음과 같습니다. rect 와 child 가 required 이므로 넣어 주어야 겠죵
PositionedTransition(
rect: RelativeRectTween(
// fromSize : 사이즈 줄이기 키우기
// fromLTWH : 위치 바꾸기
begin: RelativeRect.fromLTRB(
0, 0, smallLogo, smallLogo,
),
end: RelativeRect.fromSize(
Rect.fromLTWH(biggest.width - bigLogo,
biggest.height - bigLogo, bigLogo, bigLogo),
biggest,
),
).animate(CurvedAnimation(
parent: _animation,
curve: Curves.elasticInOut,
),
),
child: Image.asset('assets/image.jpeg'),
)
천천히 봅시다.
RelativeRectTween 입니다. begin , end 즉 처음 시작 위치와 종료 위치를 지정할 수 있습니다.
Tween 을 상속 받고 있으며 begin 과 end 에는 RelativeRect 클래스 의 fromSize 또는 fromLTRB를 지정하여 사용할 수 있습니다. 또한 fromRect , fromDirectional 다양하게 생성이 가능하네요.
// fromSize : 사이즈
// fromLTWH : 위치 바꾸기
begin: RelativeRect.fromLTRB(
0, 0, smallLogo, smallLogo,
),
end: RelativeRect.fromSize(
Rect.fromLTWH(biggest.width - bigLogo,
biggest.height - bigLogo, bigLogo, bigLogo),
biggest,
),
RelativeRectTween 함수중 animate 라는 함수가 있는데 이는 _AnimatedEvalution 즉 Animation 구현체를 리턴합니다.
Animation<T> animate(Animation<double> parent) {
return _AnimatedEvaluation<T>(parent, this);
}
이제 parent 에는 저희의 Animation를 넣으면 되겠네요!!
RelativeRectTween().animate(_animation),
물론 예제의 CurvedAnimation 을 사용하셔도 무방합니다. [물론 컨트롤러를 그냥 좀 바꿔야 되겠지만 ㅎㅎ 귀찮으니 패스]
RelativeRectTween().animate(CurvedAnimation(
parent: _animationController,
curve: Curves.elasticInOut,
),
child 에는 움직일 이미지나 등등 아무 Widget 을 넣도록 되어있네요.
child: Image.asset('assets/image.jpeg')
해당 PositionedAnimation 의 동영상입니다.
'flutter & dart' 카테고리의 다른 글
flutter & dart - AnimatedSwicher , AnimatedOpacity , AnimatedDefaultTextStyle (0) | 2024.04.03 |
---|---|
flutter & dart - AnimatedContainer (0) | 2024.04.03 |
flutter & dart - TabBar , DefaultTabController (0) | 2024.04.02 |
flutter & dart - Key (중요) , 이니셜라이저를 사용하는 이유 (0) | 2024.04.02 |
flutter & dart - 아코디언 같은 ExpantionPanelList (0) | 2024.04.02 |