插件介绍

web_animations 是一个功能丰富的 Flutter 动画示例集合,展示了 Flutter 框架中各种动画功能和实现方式。这个包提供了基础动画组件和高级动画效果的完整示例,帮助开发者学习和理解 Flutter 动画系统的核心概念和最佳实践。

主要功能特点:

  • 提供多种基础动画组件示例,如 AnimatedContainerAnimationControllerTween
  • 包含丰富的高级动画效果,如卡片滑动、轮播图、英雄动画、物理模拟动画等
  • 支持多种动画类型:显式动画、隐式动画、序列动画、重复动画等
  • 提供完整的代码示例和使用场景,便于开发者学习和参考
  • 采用模块化结构,将不同类型的动画示例分类组织,便于查找和使用
  • 支持 Flutter Web 平台,可直接在浏览器中运行和预览动画效果

使用步骤

包的引入

由于这是一个自定义修改版本的三方库,需要以 git 形式引入。在引用的项目中,在 pubspec.yaml 文件的 dependencies 部分新增以下配置:

dependencies:
  web_animations:
    git:
      url: "https://atomgit.com/"
      path: "packages/web_animations/web_animations"

然后执行以下命令获取依赖:

flutter pub get

API 调用

web_animations 主要提供以下核心功能模块:

1. 基础动画组件
AnimatedContainer

AnimatedContainer 是最常用的隐式动画组件之一,能够自动处理容器属性变化的动画效果:

import 'package:flutter/material.dart';
import 'dart:math';

class MyAnimatedContainer extends StatefulWidget {
  const MyAnimatedContainer({super.key});

  
  State<MyAnimatedContainer> createState() => _MyAnimatedContainerState();
}

class _MyAnimatedContainerState extends State<MyAnimatedContainer> {
  late Color color;
  late double borderRadius;
  late double margin;

  
  void initState() {
    super.initState();
    color = Colors.deepPurple;
    borderRadius = 20.0;
    margin = 10.0;
  }

  void change() {
    setState(() {
      color = Color(0xFFFFFFFF & Random().nextInt(0xFFFFFFFF));
      borderRadius = Random().nextDouble() * 64;
      margin = Random().nextDouble() * 32;
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AnimatedContainer'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: 200,
              height: 200,
              child: AnimatedContainer(
                margin: EdgeInsets.all(margin),
                decoration: BoxDecoration(
                  color: color,
                  borderRadius: BorderRadius.circular(borderRadius),
                ),
                duration: const Duration(milliseconds: 500),
                curve: Curves.easeInOut,
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => change(),
              child: const Text('Change Animation'),
            ),
          ],
        ),
      ),
    );
  }
}
AnimationController

AnimationController 是显式动画的核心控制器,用于控制动画的播放、暂停、反转等:

import 'package:flutter/material.dart';

class MyAnimationController extends StatefulWidget {
  const MyAnimationController({super.key});

  
  State<MyAnimationController> createState() => _MyAnimationControllerState();
}

class _MyAnimationControllerState extends State<MyAnimationController>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller);
  }

  
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Animation Controller'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedBuilder(
              animation: _animation,
              builder: (context, child) {
                return Transform.rotate(
                  angle: _animation.value * 2 * 3.14159,
                  child: Container(
                    width: 100,
                    height: 100,
                    color: Colors.blue,
                  ),
                );
              },
            ),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () => _controller.forward(),
                  child: const Text('Forward'),
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  onPressed: () => _controller.reverse(),
                  child: const Text('Reverse'),
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  onPressed: () => _controller.reset(),
                  child: const Text('Reset'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
2. 高级动画效果
Hero 动画

Hero 动画用于在页面之间平滑过渡共享的元素:

import 'package:flutter/material.dart';

class HeroAnimationScreen extends StatelessWidget {
  const HeroAnimationScreen({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Hero Animation'),
      ),
      body: GestureDetector(
        child: Hero(
          tag: 'hero-image',
          child: Container(
            height: 100,
            width: 100,
            decoration: const BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.blue,
            ),
            child: const FlutterLogo(),
          ),
        ),
        onTap: () => Navigator.of(context).push<void>(
          MaterialPageRoute(builder: (context) => const HeroDetailScreen()),
        ),
      ),
    );
  }
}

class HeroDetailScreen extends StatelessWidget {
  const HeroDetailScreen({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.lightBlue,
      appBar: AppBar(),
      body: Center(
        child: Hero(
          tag: 'hero-image',
          child: Container(
            height: 200,
            width: 200,
            decoration: const BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.white,
            ),
            child: const FlutterLogo(size: 100),
          ),
        ),
      ),
    );
  }
}
卡片滑动动画

实现卡片的滑动和切换效果:

import 'package:flutter/material.dart';
import 'dart:math';

class CardSwipeScreen extends StatefulWidget {
  const CardSwipeScreen({super.key});

  
  State<CardSwipeScreen> createState() => _CardSwipeScreenState();
}

class _CardSwipeScreenState extends State<CardSwipeScreen> {
  late List<Color> cardColors;
  late List<String> cardTexts;

  
  void initState() {
    super.initState();
    cardColors = [
      Colors.red,
      Colors.blue,
      Colors.green,
      Colors.yellow,
      Colors.purple,
    ];
    cardTexts = [
      'Card 1',
      'Card 2',
      'Card 3',
      'Card 4',
      'Card 5',
    ];
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Card Swipe'),
      ),
      body: Center(
        child: SizedBox(
          height: 400,
          width: 300,
          child: Stack(
            children: [
              for (int i = cardColors.length - 1; i >= 0; i--) ...{
                Positioned(
                  top: i * 20.0,
                  left: 0,
                  right: 0,
                  child: GestureDetector(
                    onPanUpdate: (details) {
                      setState(() {
                        // 实现滑动逻辑
                      });
                    },
                    onPanEnd: (details) {
                      setState(() {
                        // 实现滑动结束逻辑
                      });
                    },
                    child: Card(
                      elevation: 10,
                      color: cardColors[i],
                      child: SizedBox(
                        height: 300,
                        child: Center(
                          child: Text(
                            cardTexts[i],
                            style: const TextStyle(
                              fontSize: 30,
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              },
            ],
          ),
        ),
      ),
    );
  }
}

鸿蒙适配注意事项

在鸿蒙环境中使用 web_animations 时,需要注意以下几点:

  1. 性能优化:鸿蒙系统对动画性能要求较高,建议在使用复杂动画时注意优化性能,避免过度使用导致应用卡顿。

  2. 屏幕适配:鸿蒙设备有多种屏幕尺寸和分辨率,需要确保动画效果在不同设备上都能正常显示。

  3. 资源加载:动画中使用的图片、字体等资源需要正确配置,确保在鸿蒙系统中能够正常加载。

  4. 权限处理:如果动画效果涉及到系统功能(如传感器数据),需要确保应用具有相应的权限。

  5. 平台特定代码:避免在动画代码中使用鸿蒙平台不支持的 API 或功能。

示例应用

以下是一个完整的示例应用,展示了如何在鸿蒙系统中使用 web_animations 包:

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

// 导入动画组件
import 'package:web_animations/src/basics/animated_container.dart';
import 'package:web_animations/src/misc/hero_animation.dart';

void main() {
  runApp(const AnimationSamplesApp());
}

final router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const HomePage(),
      routes: [
        GoRoute(
          path: 'animated_container',
          builder: (context, state) => const AnimatedContainerDemo(),
        ),
        GoRoute(
          path: 'hero_animation',
          builder: (context, state) => const HeroAnimationDemo(),
        ),
      ],
    ),
  ],
);

class AnimationSamplesApp extends StatelessWidget {
  const AnimationSamplesApp({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Flutter Animations for HarmonyOS',
      theme: ThemeData(
        colorSchemeSeed: Colors.deepPurple,
        useMaterial3: true,
      ),
      routerConfig: router,
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Animation Samples'),
      ),
      body: ListView(
        children: [
          ListTile(
            title: const Text('Animated Container'),
            onTap: () => context.go('/animated_container'),
          ),
          ListTile(
            title: const Text('Hero Animation'),
            onTap: () => context.go('/hero_animation'),
          ),
        ],
      ),
    );
  }
}

总结

web_animations 是一个功能强大的 Flutter 动画示例集合,提供了丰富的动画组件和效果示例,帮助开发者学习和掌握 Flutter 动画系统。无论是基础的隐式动画还是复杂的高级动画效果,这个包都提供了完整的实现示例和最佳实践。

在鸿蒙系统中使用 web_animations 时,开发者需要注意性能优化、屏幕适配、资源加载等问题,确保动画效果在鸿蒙设备上能够流畅运行。通过合理使用这个包提供的动画组件和效果,开发者可以为鸿蒙应用添加丰富的视觉效果和交互体验。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐