명시적 애니메이션 및 Hero
`AnimationController`와 `Tween`을 사용한 명시적 애니메이션을 익히고, Hero 위젯으로 매력적인 공유 요소 전환을 만듭니다.
명시적 애니메이션 및 Hero은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to Explicit Animations
Welcome to explicit animations! Unlike implicit animations (which animate automatically when properties change), explicit animations give you full control.
You define how and when an animation runs, its duration, and its curve. This is powerful for complex, custom effects.
AnimationController: The Conductor
At the heart of explicit animations is the AnimationController. Think of it as the conductor of an orchestra, managing the animation's playback.
- It generates a new value every frame.
- It controls the animation's duration.
- It can be forwarded, reversed, or repeated.
It needs a TickerProviderStateMixin to synchronize with the screen refresh rate.
Setting Up AnimationController
You typically initialize an AnimationController in your widget's initState and dispose of it in dispose to prevent memory leaks.
Here's a basic setup:
import 'package:flutter/material.dart';
class MyAnimationScreen extends StatefulWidget {
@override
_MyAnimationScreenState createState() => _MyAnimationScreenState();
}
class _MyAnimationScreenState extends State<MyAnimationScreen> with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Controller Setup')),
body: Center(
child: Text('Animation controller ready!')
),
);
}
}
void main() {
runApp(MaterialApp(home: MyAnimationScreen()));
}Tween: Defining the Range
While AnimationController provides a value from 0.0 to 1.0 over its duration, a Tween (short for 'in-betweening') defines the range of values you actually want to animate.
- A
Tweenmaps the controller's 0.0-1.0 range to your desiredbeginandendvalues. - Common types include
Tween,ColorTween, andSizeTween.
Connecting Tween & Controller
To use a Tween, you create an Animation object by calling animate() on the Tween, passing your AnimationController.
This Animation object will then yield values within your defined range as the controller progresses from 0.0 to 1.0.
import 'package:flutter/material.dart';
class MyTweenExample extends StatefulWidget {
@override
_MyTweenExampleState createState() => _MyTweenExampleState();
}
class _MyTweenExampleState extends State<MyTweenExample> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
// Define a tween that animates a double from 0.0 to 200.0
_animation = Tween<double>(begin: 0.0, end: 200.0).animate(_controller);
_controller.forward(); // Start the animation
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Tween Connection')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Animation value: ${_animation.value.toStringAsFixed(2)}'),
// Note: This won't update automatically without a listener or AnimatedBuilder yet
],
)
),
);
}
}
void main() {
runApp(MaterialApp(home: MyTweenExample()));
}AnimatedBuilder for Efficiency
To make your UI react to animation values, you could use addListener and setState. However, AnimatedBuilder is a more efficient widget for this.
It rebuilds only the animating part of your widget tree, preventing unnecessary rebuilds of static widgets.
import 'package:flutter/material.dart';
class MyAnimatedBuilder extends StatefulWidget {
@override
_MyAnimatedBuilderState createState() => _MyAnimatedBuilderState();
}
class _MyAnimatedBuilderState extends State<MyAnimatedBuilder> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
_animation = Tween<double>(begin: 50.0, end: 150.0).animate(_controller);
_controller.forward(); // Start animation
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('AnimatedBuilder Demo')),
body: Center(
child: AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Container(
width: _animation.value,
height: _animation.value,
color: Colors.blue,
child: Center(child: Text('Size', style: TextStyle(color: Colors.white))),
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller.reset();
_controller.forward();
},
child: Icon(Icons.play_arrow),
),
);
}
}
void main() {
runApp(MaterialApp(home: MyAnimatedBuilder()));
}Introducing Hero Widgets
Hero widgets enable a stunning shared-element transition between routes (screens). When you navigate from one screen to another, a Hero widget flies from its position on the first screen to its new position on the second screen.
This creates a visually appealing and intuitive user experience, indicating a connection between the two screens.
Implementing Hero Transitions
To use a Hero widget, you need two widgets (one on each screen) with the exact same tag. When navigation occurs between these screens, Flutter handles the animation automatically.
The tag must be unique across all Hero widgets currently on the screen.
import 'package:flutter/material.dart';
// First Screen
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('First Screen')),
body: Center(
child: GestureDetector(
onTap: () {
Navigator.push(
context, MaterialPageRoute(builder: (_) => SecondScreen()));
},
child: Hero(
tag: 'hero-image-tag',
child: Container(
width: 100,
height: 100,
color: Colors.red,
child: Center(child: Text('Tap Me', style: TextStyle(color: Colors.white))),
),
),
),
),
);
}
}
// Second Screen
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Second Screen')),
body: Center(
child: Hero(
tag: 'hero-image-tag',
child: Container(
width: 300,
height: 300,
color: Colors.blue,
child: Center(child: Text('Big Hero', style: TextStyle(color: Colors.white))),
),
),
),
);
}
}
void main() {
runApp(MaterialApp(home: FirstScreen()));
}Explicit Animations & Heroes Quiz
Which of the following statements about AnimationController and Hero widgets are true?
Recap: Explicit Animations & Heroes
In this lesson, you mastered explicit animations and Hero widgets:
- Explicit Animations: Offer fine-grained control over animation playback using
AnimationControllerandTween. AnimationController: Manages animation duration and playback (forward, reverse).Tween: Defines the specific range of values an animation will traverse.AnimatedBuilder: An efficient way to rebuild only the animated parts of your UI.HeroWidgets: Create captivating shared-element transitions between screens using matchingtagproperties.
You now have powerful tools to create dynamic and engaging user interfaces!
자주 묻는 질문
“명시적 애니메이션 및 Hero” 강의는 무료인가요?
네 — “명시적 애니메이션 및 Hero” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“명시적 애니메이션 및 Hero”에서 뭘 배우나요?
`AnimationController`와 `Tween`을 사용한 명시적 애니메이션을 익히고, Hero 위젯으로 매력적인 공유 요소 전환을 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“명시적 애니메이션 및 Hero” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- CustomPainter 및 Canvas
- 암시적 애니메이션
- 명시적 애니메이션 및 Hero
- 엇갈린 애니메이션과 물리 기반 애니메이션