『Flutter-绘制篇』实现炫酷的雨雪特效
import 'dart:math' as math;
import 'package:flutter/material.dart';
class RainSnowEffect extends StatefulWidget {
@override
_RainSnowEffectState createState() => _RainSnowEffectState();
}
class _RainSnowEffectState extends State<RainSnowEffect>
with SingleTickerProviderStateMixin {
AnimationController _controller;
List<Drop> _drops = [];
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 10),
vsync: this,
)..addListener(() {
setState(() {
_drops.forEach((drop) => drop.update(1.0 / _controller.duration.inMilliseconds));
});
});
_controller.forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_drops.length < 200) {
_drops.add(Drop(random: math.Random()));
}
return Scaffold(
body: Stack(
children: _drops.map((drop) {
return Positioned(
left: drop.x,
top: drop.y,
child: drop.isRaining ? Rain() : Snow(),
);
}).toList(),
),
);
}
}
class Drop {
double x;
double y;
double dx;
bool isRaining;
Drop({math.Random random}) {
x = random.nextDouble() * 375;
y = random.nextDouble() * 600;
dx = random.nextDouble() * 1.5 + 0.5;
isRaining = random.nextBool();
}
void update(double dt) {
x += dx * dt;
y += dt / 20;
if (y > 600) {
y = -50;
isRaining = !isRaining;
}
}
}
class Rain extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
width: 5,
height: 20,
decoration: BoxDecoration(
color: Colors.blue,
shape: BoxShape.circle,
),
);
}
}
class Snow extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
width: 5,
height: 5,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
);
}
}
这段代码实现了在Flutter中创建一个雨雪特效的示例。它使用了AnimationController
来控制水滴的更新,并且通过随机值确定水滴的起始位置、速度以及是雨还是雪。当水滴移动到屏幕外部时,会重新生成新的位置和形态。这个例子展示了如何使用Widget、AnimationController和状态管理来创建一个动态的视觉效
评论已关闭