惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
M
MIT News - Artificial intelligence
MyScale Blog
MyScale Blog
博客园_首页
G
Google Developers Blog
博客园 - 【当耐特】
美团技术团队
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
Vercel News
Vercel News
小众软件
小众软件
博客园 - 司徒正美
雷峰网
雷峰网
T
Tailwind CSS Blog
V
V2EX
博客园 - 三生石上(FineUI控件)
F
Fortinet All Blogs
罗磊的独立博客
量子位
P
Proofpoint News Feed
Microsoft Azure Blog
Microsoft Azure Blog
月光博客
月光博客
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Flutter Animation Deep Dive — AnimationController, Custom...
kanta13jp1 · 2026-05-01 · via DEV Community

kanta13jp1

Flutter Animation Deep Dive — AnimationController, Custom Tweens, and Physics Simulations

Flutter's animation system divides into two layers: implicit (value-driven, automatic) and explicit (controller-driven, precise). Knowing when to use each — and how to compose them — separates polished apps from janky ones.

Implicit Animations: Let the Framework Drive

AnimatedContainer(
  duration: const Duration(milliseconds: 400),
  curve: Curves.easeOutCubic,
  width: _expanded ? 300 : 100,
  height: _expanded ? 200 : 60,
  decoration: BoxDecoration(
    color: _expanded ? Colors.indigo : Colors.indigo.shade200,
    borderRadius: BorderRadius.circular(_expanded ? 16 : 8),
  ),
  child: const Center(child: Text('Tap me')),
)

Enter fullscreen mode Exit fullscreen mode

Flutter ships 20+ animated widgets (AnimatedSwitcher, AnimatedOpacity, AnimatedPadding, …). Prefer them. Reach for AnimationController only when implicit widgets can't express what you need.

Explicit Animations: AnimationController

class _FadeSlideState extends State<FadeSlide>
    with SingleTickerProviderStateMixin {
  late AnimationController _ctrl;
  late Animation<double> _opacity;
  late Animation<Offset> _slide;

  @override
  void initState() {
    super.initState();
    _ctrl = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this, // prevents off-screen rendering
    );
    final curved = CurvedAnimation(parent: _ctrl, curve: Curves.easeOut);

    _opacity = Tween<double>(begin: 0, end: 1).animate(curved);
    _slide = Tween<Offset>(
      begin: const Offset(0, 0.15),
      end: Offset.zero,
    ).animate(curved);
  }

  @override
  void dispose() {
    _ctrl.dispose(); // critical: prevents ticker leak
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _slide,
      child: FadeTransition(opacity: _opacity, child: widget.child),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Use SingleTickerProviderStateMixin for one controller; TickerProviderStateMixin for multiple.

Custom Tweens

// HSL color interpolation (smoother hue transitions than RGB lerp)
class HslColorTween extends Tween<Color> {
  HslColorTween({required super.begin, required super.end});

  @override
  Color lerp(double t) {
    final b = HSLColor.fromColor(begin!);
    final e = HSLColor.fromColor(end!);
    return HSLColor.fromAHSL(
      lerpDouble(b.alpha, e.alpha, t)!,
      lerpDouble(b.hue, e.hue, t)!,
      lerpDouble(b.saturation, e.saturation, t)!,
      lerpDouble(b.lightness, e.lightness, t)!,
    ).toColor();
  }
}

final colorAnim = HslColorTween(begin: Colors.blue, end: Colors.pink)
    .animate(CurvedAnimation(parent: _ctrl, curve: Curves.easeInOut));

Enter fullscreen mode Exit fullscreen mode

Override lerp to control how values interpolate between begin and end.

Sequencing with Interval

// One controller, three elements with staggered timing
_fade = Tween<double>(begin: 0, end: 1).animate(
  CurvedAnimation(parent: _ctrl, curve: const Interval(0.0, 0.4)),
);
_slide = Tween<Offset>(begin: const Offset(0, 0.2), end: Offset.zero).animate(
  CurvedAnimation(parent: _ctrl, curve: const Interval(0.2, 0.7)),
);
_scale = Tween<double>(begin: 0.8, end: 1.0).animate(
  CurvedAnimation(
    parent: _ctrl,
    curve: const Interval(0.5, 1.0, curve: Curves.elasticOut),
  ),
);

Enter fullscreen mode Exit fullscreen mode

Interval values (0.0–1.0) map to fractions of the controller's total duration.

Physics-Based Animations: SpringSimulation

void _onTap() {
  final spring = SpringDescription(mass: 1, stiffness: 200, damping: 15);
  final sim = SpringSimulation(spring, _ctrl.value, 1.0, 0);
  _ctrl.animateWith(sim);
}

void _onRelease() {
  final spring = SpringDescription(mass: 1, stiffness: 200, damping: 15);
  final sim = SpringSimulation(spring, _ctrl.value, 0.0, 0);
  _ctrl.animateWith(sim);
}

Enter fullscreen mode Exit fullscreen mode

Pass the current drag velocity as the fourth argument to SpringSimulation to create seamless hand-off from gesture to physics.

AnimatedBuilder + CustomPainter

class WavePainter extends CustomPainter {
  final double phase;
  WavePainter(this.phase);

  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()..moveTo(0, size.height / 2);
    for (double x = 0; x <= size.width; x++) {
      path.lineTo(x, size.height / 2 + 30 * sin(x / size.width * 2 * pi + phase));
    }
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.close();
    canvas.drawPath(path, Paint()..color = Colors.indigo.withOpacity(0.4));
  }

  @override
  bool shouldRepaint(WavePainter old) => old.phase != phase;
}

// Isolate repaint cost with RepaintBoundary
AnimatedBuilder(
  animation: _ctrl,
  builder: (_, __) => RepaintBoundary(
    child: CustomPaint(
      painter: WavePainter(_ctrl.value * 2 * pi),
      size: const Size(double.infinity, 120),
    ),
  ),
)

Enter fullscreen mode Exit fullscreen mode

Hero Animations

// Source route
Hero(
  tag: 'product-${product.id}',
  child: Image.network(product.imageUrl),
)

// Destination route — same tag is enough
Hero(
  tag: 'product-${product.id}',
  flightShuttleBuilder: (_, anim, direction, from, to) =>
      FadeTransition(opacity: anim, child: to),
  child: Image.network(product.imageUrl, fit: BoxFit.cover),
)

Enter fullscreen mode Exit fullscreen mode

flightShuttleBuilder lets you control exactly what renders during the shared-element flight.

Performance Checklist

Issue Avoid Use Instead
Rebuilding whole tree setState inside animation AnimatedBuilder
Heavy subtree in animation scope Large widgets that repaint every frame RepaintBoundary
Image decode per frame Uncached network images precacheImage
Opacity blending Opacity(opacity: val) FadeTransition (preserves raster cache)

Profile with flutter run --profile and DevTools Frame Chart before optimizing.

Summary

  1. Start implicitAnimatedContainer and friends cover most cases
  2. Go explicit when you need precise timing → AnimationController + Tween + Interval
  3. Add feelSpringSimulation for physics-based touch response
  4. Custom visualsCustomPainter + RepaintBoundary
  5. Screen transitionsHero for continuity

Animation is UI vocabulary — it explains why something changed, not just that it changed. Get the curve and duration right, and everything else follows.