Flutter雪花特效或自定义动画插件snowfall_or_anythings的使用

Flutter雪花特效或自定义动画插件snowfall_or_anythings的使用

一个用于在您的应用程序中创建漂亮的雪花或其他粒子效果的 Flutter 包。

特性

  • 易于使用
  • 可自定义的粒子
  • 高性能

安装

pubspec.yaml 文件中添加以下内容:

dependencies:
    snowfall_or_anythings: ^0.0.4

然后运行 flutter pub get 来安装该包。

使用

基本示例

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Snowfall Demo'),
      ),
      body: const SnowfallOrAnythings(
        numberOfParticles: 200,
        particleSize: 4.0,
        particleSpeed: 0.8,
        particleType: ParticleType.snowflake,
      ),
    );
  }
}

结果

Gravando 2024-11-24 010503

自定义粒子

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('CustomPainter Demo'),
      ),
      body: SnowfallOrAnythings(
        particleColor: Colors.green,
        numberOfParticles: 150,
        particleSize: 10.0,
        particleSpeed: 2.0,
        customPainter: ({required particles}) => CustomParticlePainter(particles),
      ),
    );
  }
}

class CustomParticlePainter extends CustomPainter {
  final List<Particle> particles;

  CustomParticlePainter(this.particles);

  [@override](/user/override)
  void paint(Canvas canvas, Size size) {
    final paint = Paint();

    for (final particle in particles) {
      paint.color = particle.color;
      canvas.drawRect(
        Rect.fromCenter(
          center: Offset(particle.x, particle.y),
          width: particle.size,
          height: particle.size,
        ),
        paint,
      );
    }
  }

  [@override](/user/override)
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

完整示例代码

import 'package:example/pages/custom_paint_page.dart';
import 'package:example/pages/snow_page.dart';
import 'package:example/pages/widget_page.dart';
import 'package:flutter/material.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Particle Demo',
      theme: ThemeData.dark(),
      home: const MainPage(),
    );
  }
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Particle Effects Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const SnowPage(),
                  ),
                );
              },
              child: const Text('Snowfall Demo'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const CustomPaintpage(),
                  ),
                );
              },
              child: const Text('CustomPainter Demo'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const WidgetParticlePage(),
                  ),
                );
              },
              child: const Text('Widget Particle Demo'),
            ),
          ],
        ),
      ),
    );
  }
}

class CustomPaintDemo {
  const CustomPaintDemo();
}

更多关于Flutter雪花特效或自定义动画插件snowfall_or_anythings的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter雪花特效或自定义动画插件snowfall_or_anythings的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,我可以为你提供一个使用Flutter创建雪花特效的代码案例。在这个例子中,我们将使用Flutter的动画功能来实现一个简单的雪花飘落效果,而不是依赖第三方插件。

首先,确保你的Flutter环境已经设置好,并且创建了一个新的Flutter项目。然后,你可以按照以下步骤在你的项目中实现雪花特效。

  1. 创建雪花组件

首先,我们定义一个Snowflake组件,它表示单个雪花。雪花将有一个随机的大小、速度和方向。

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

class Snowflake extends StatefulWidget {
  @override
  _SnowflakeState createState() => _SnowflakeState();
}

class _SnowflakeState extends State<Snowflake> with SingleTickerProviderStateMixin {
  double size;
  double speed;
  Offset position;
  double angle;
  double velocityX;
  double velocityY;

  @override
  void initState() {
    super.initState();
    Random random = Random();
    size = random.nextDouble() * 10 + 5; // Random size between 5 and 15
    speed = random.nextDouble() * 2 + 1; // Random speed between 1 and 3
    position = Offset(random.nextDouble() * MediaQuery.of(context).size.width, -size);
    angle = random.nextDouble() * 2 * pi; // Random angle between 0 and 2π
    velocityX = cos(angle) * speed;
    velocityY = sin(angle) * speed + speed / 2; // Slightly faster vertically

    _animateSnowflake();
  }

  void _animateSnowflake() async {
    while (position.dy < MediaQuery.of(context).size.height + size) {
      setState(() {
        position = Offset(position.dx + velocityX, position.dy + velocityY);
      });
      await Future.delayed(Duration(milliseconds: 30)); // Adjust this for smoother animation
    }
    // Reset position when snowflake falls out of view
    setState(() {
      position = Offset(Random().nextDouble() * MediaQuery.of(context).size.width, -size);
      _animateSnowflake();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: position.dx,
      top: position.dy,
      child: Container(
        width: size,
        height: size,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white.withOpacity(0.7),
        ),
      ),
    );
  }
}
  1. 在主屏幕中使用雪花组件

接下来,在你的主屏幕(通常是MyHomePage)中,使用Stack组件来叠加多个雪花,并创建一个按钮来启动或停止雪花动画(尽管在这个例子中,雪花动画是持续进行的)。

import 'package:flutter/material.dart';
import 'snowflake.dart'; // Import the Snowflake widget

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Snowfall Effect'),
      ),
      body: Stack(
        children: List.generate(50, (index) => Snowflake()), // Generate 50 snowflakes
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: MyHomePage(),
  ));
}

在这个例子中,我们创建了50个雪花,每个雪花都有自己的大小、速度和运动轨迹。Snowflake组件在initState方法中启动了一个无限循环的动画,当雪花落出屏幕时,它会重置位置并继续动画。

你可以根据需要调整雪花的数量、大小、速度和动画帧率(通过调整Future.delayed的延迟时间)来达到你想要的视觉效果。这个实现方式虽然简单,但已经能够展示出一个基本的雪花飘落效果。

回到顶部