You need to enable JavaScript to run this app. Flutter Web开发:作品集网站如何实现下滑滚动时的元素淡入动画
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web开发:作品集网站如何实现下滑滚动时的元素淡入动画

滚动触发淡入动画实现方案

核心实现逻辑

两类成熟路径可以直接落地,不需要从零手搓复杂的滚动偏移计算:

  • 纯原生实现:通过RenderBox获取元素全局位置,结合当前视口边界做触发判定,搭配Flutter内置的动画组件就能实现完整效果,无任何第三方依赖,适合结构简单的个人作品集页面。
  • 检测插件适配:如果遇到长列表、嵌套滚动、窗口尺寸动态变化的复杂场景,直接引入轻量的可视区域检测能力,比自写位置计算的兼容性更强,不会出现不同屏幕下触发时机错位的问题。

可直接复用的代码示例

下面是封装好的无依赖可复用组件,实现和参考效果一致的滚动触发淡入上移动画:

import 'package:flutter/material.dart';

class ScrollTriggerFadeIn extends StatefulWidget {
  final Widget child;
  // 元素距离视口底部多少比例时触发动画
  final double triggerOffset;
  final Duration animationDuration;

  const ScrollTriggerFadeIn({
    super.key,
    required this.child,
    this.triggerOffset = 0.15,
    this.animationDuration = const Duration(milliseconds: 600),
  });

  @override
  State<ScrollTriggerFadeIn> createState() => _ScrollTriggerFadeInState();
}

class _ScrollTriggerFadeInState extends State<ScrollTriggerFadeIn>
    with SingleTickerProviderStateMixin {
  late AnimationController _animController;
  late Animation<double> _opacityAnim;
  late Animation<Offset> _slideAnim;
  // 标记是否已经触发过动画,避免重复播放
  bool _isTriggered = false;

  @override
  void initState() {
    super.initState();
    _animController = AnimationController(
      vsync: this,
      duration: widget.animationDuration,
    );
    // 透明度从0过渡到1
    _opacityAnim = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _animController, curve: Curves.easeOutCubic),
    );
    // 从下方位置滑入最终位置
    _slideAnim = Tween<Offset>(
      begin: const Offset(0, 0.15),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(parent: _animController, curve: Curves.easeOutCubic),
    );
    // 页面初始加载完成后做一次状态检测
    WidgetsBinding.instance.addPostFrameCallback((_) => _checkIfVisible());
  }

  void _checkIfVisible() {
    if (_isTriggered || !mounted) return;
    // 获取元素在全局坐标系中的位置
    final renderBox = context.findRenderObject() as RenderBox;
    final elementGlobalPos = renderBox.localToGlobal(Offset.zero);
    // 获取当前视口高度
    final viewportHeight = MediaQuery.of(context).size.height;
    // 触发判定:元素顶部滚动到距离视口底部指定偏移量时启动动画
    if (elementGlobalPos.dy < viewportHeight * (1 - widget.triggerOffset)) {
      _isTriggered = true;
      _animController.forward();
    }
  }

  @override
  void dispose() {
    _animController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 滚动时触发可见性检测
    return NotificationListener<ScrollNotification>(
      onNotification: (notification) {
        _checkIfVisible();
        return true;
      },
      child: AnimatedBuilder(
        animation: _animController,
        builder: (context, _) {
          return Opacity(
            opacity: _opacityAnim.value,
            child: SlideTransition(
              position: _slideAnim,
              child: widget.child,
            ),
          );
        },
      ),
    );
  }
}

// 组件使用示例
class PortfolioHomePage extends StatelessWidget {
  const PortfolioHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 首屏内容,无需触发动画
            SizedBox(
              height: MediaQuery.of(context).size.height * 0.9,
              child: const Center(child: Text("个人介绍首屏", style: TextStyle(fontSize: 24))),
            ),
            // 后续内容块直接用ScrollTriggerFadeIn包裹即可
            ScrollTriggerFadeIn(
              child: Container(
                height: 320,
                margin: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Center(child: Text("项目展示模块1")),
              ),
            ),
            ScrollTriggerFadeIn(
              child: Container(
                height: 320,
                margin: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Center(child: Text("项目展示模块2")),
              ),
            ),
            // 其余模块重复上述结构即可
          ],
        ),
      ),
    );
  }
}

效果调优注意事项

  • 触发时机可以通过triggerOffset参数调整:数值越大,元素需要滚动到更靠近视口中心的位置才会触发动画,比如设为0.2就是元素进入视口20%高度时启动效果。
  • 匹配参考示例效果时,可以把初始垂直偏移调整为30像素,动画曲线用easeOutCubic,完全可以还原参考动图里顺滑的淡入上移质感。
  • 性能优化:当页面内容长度超过3个屏幕高度时,不要在每个组件的build方法里频繁做位置计算,可通过全局滚动控制器统一做触发判定,减少不必要的渲染开销。如果是超长列表,优先选用可视区域占比检测的方案,避免滚动卡顿。

内容的提问来源于stack exchange,提问作者Ali Azimoshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 22:27:03