雪花动画:
import 'dart:math';
import 'package:flutter/material.dart';
class AnimatedSnowPage extends StatefulWidget {
const AnimatedSnowPage({Key? key}) : super(key: key);
@override
State<AnimatedSnowPage> createState() => _AnimatedSnowPageState();
}
class _AnimatedSnowPageState extends State<AnimatedSnowPage>
with SingleTickerProviderStateMixin {
AnimationController? _controller;
final List<Snowflake> _snowflakes =
List.generate(1000, (index) => Snowflake());
@override
void initState() {
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
)..repeat();
super.initState();
}
@override
void dispose() {
_controller!.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
width: double.infinity,
height: double.infinity,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.blue, Colors.lightBlue, Colors.white],
stops: [0.0, 0.7, 0.95],
),
),
child: AnimatedBuilder(
animation: _controller!,
builder: (BuildContext context, Widget? child) {
for (var snow in _snowflakes) {
snow.fall();
}
return CustomPaint(
painter: MyPainter(_snowflakes),
);
},
),
),
),
);
}
}
class MyPainter extends CustomPainter {
final whitePaint = Paint()..color = Colors.white;
final List<Snowflake> _snowflakes;
MyPainter(this._snowflakes);
@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(size.center(const Offset(0, 150)), 60, whitePaint);
canvas.drawOval(
Rect.fromCenter(
center: size.center(const Offset(0, 320)),
width: 200,
height: 250,
),
whitePaint);
for (var snowflake in _snowflakes) {
canvas.drawCircle(
Offset(snowflake.x, snowflake.y), snowflake.radius, whitePaint);
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
class Snowflake {
double x = Random().nextDouble() * 400;
double y = Random().nextDouble() * 800;
double radius = Random().nextDouble() * 2 + 2;
double velocity = Random().nextDouble() * 4 + 2;
fall() {
y += velocity;
if (y > 800) {
y = 0;
x = Random().nextDouble() * 400;
y = Random().nextDouble() * 800;
radius = Random().nextDouble() * 2 + 2;
velocity = Random().nextDouble() * 4 + 2;
}
}
}