플러터에서는 애니메이션을 만들 수 있다.
그런데 똑같은 애니메이션인데,
매번 필요한 화면에서 initState()에서 초기화 해주고...
dispose()에서 해제시키고...
매우 귀찮다
결국 방법은 있었으니, 잊지 않기 위해서.
import 'package:flutter/material.dart';
mixin DoubleFadeOutAnimationMixin<T extends StatefulWidget>
on State<T>, TickerProviderStateMixin<T> {
late AnimationController animationController01;
late AnimationController animationController02;
late Animation<double> animation01;
late Animation<double> animation02;
void initState() {
super.initState();
animationController01 = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
animationController02 = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
animation01 = Tween<double>(begin: 1.0, end: 0.0).animate(
CurvedAnimation(
parent: animationController01,
curve: Curves.easeInOut,
),
);
animation02 = Tween<double>(begin: 1.0, end: 0.0).animate(
CurvedAnimation(
parent: animationController02,
curve: Curves.easeInOut,
),
);
}
void dispose() {
animationController01.dispose();
animationController02.dispose();
super.dispose();
}
}
dart에 있는 mixin class를 사용하면 되는데
클래스에 기능을 추가합니다. mixin은 복잡한 클래스의 계층 구조에서 코드를 재사용하는 방법 중 하나입니다.
그냥 확장(extends)해서 쓰면 되지 않음...?
하지만 dart에서는 extends로 단일 상속만 지원하기 때문에
이미 State<ScreenWidget>을 확장하고 있다면... 쓸 수가 없다.
그래서 mixin class로 만들고 이걸 함께 쓰겠다는 뜻으로 with를 쓰면 된다.
with는 여러 개를 가져다 쓸 수 있다 => 다중 상속
이놈을 실제 화면에서 쓰고 싶다면
class ExampleFadeScreen extends StatefulWidget {
const ExampleFadeScreen({super.key});
State<ExampleFadeScreen> createState() => _ExampleFadeScreenState();
}
class _ExampleFadeScreenState extends State<CoachMarkScreen> with TickerProviderStateMixin, DoubleFadeOutAnimationMixin<ExampleFadeScreen> {
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: animationController01,
builder: (context, child) {
return Opacity(
opacity: animation01.value,
child: Text('fadeout animation 01...');
);
},
);
}
}
애니메이션이 똑같다면, 이런 식으로 mixin class로 작성해두고
재사용하면 참 좋지 않을까.