0Pricing
Flutter Mobile Development · 课时

显式动画与共享元素

掌握使用 `AnimationController` 和 `Tween` 实现显式动画,并使用 Hero 组件创建引人入胜的共享元素过渡。

显式动画与共享元素 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 Tween maps the controller's 0.0-1.0 range to your desired begin and end values.
  • Common types include Tween, ColorTween, and SizeTween.

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 AnimationController and Tween.
  • 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.
  • Hero Widgets: Create captivating shared-element transitions between screens using matching tag properties.

You now have powerful tools to create dynamic and engaging user interfaces!

常见问题解答

「显式动画与共享元素」课时是免费的吗?

是的 — 「显式动画与共享元素」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。

「显式动画与共享元素」这节课中我会学到什么?

掌握使用 `AnimationController` 和 `Tween` 实现显式动画,并使用 Hero 组件创建引人入胜的共享元素过渡。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Flutter Mobile Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「显式动画与共享元素」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Flutter Mobile Development 课中编写并运行代码吗?

能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. CustomPainter 与画布
  2. 隐式动画
  3. 显式动画与共享元素
  4. 交错动画与基于物理的动画
← 返回 Flutter Mobile Development