Skip to content

Instantly share code, notes, and snippets.

@nosmirck
Created January 9, 2022 00:06
Show Gist options
  • Save nosmirck/54bce262535fc0f595f4a2d0854a082f to your computer and use it in GitHub Desktop.
Save nosmirck/54bce262535fc0f595f4a2d0854a082f to your computer and use it in GitHub Desktop.
Flutter - Lightning simulation on 9 spheres
// Lightning simulation using just box decoration
// Looks like 9 spheres being illuminated by a light source
// following the mouse cursor, just for fun.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final keys = List.generate(9, (_) => GlobalKey());
late List<RenderBox> boxes;
var _offsets = List.generate(9, (_) => Offset.zero);
void _updateLocation(PointerEvent details) {
setState(() {
boxes = keys
.map((k) => k.currentContext?.findRenderObject() as RenderBox)
.toList();
_offsets = boxes.map((box) => _getOffset(box, details.position)).toList();
});
}
Offset _getOffset(RenderBox box, Offset position) {
final size = box.size;
final boxPosition =
box.localToGlobal(Offset(size.width / 2.0, size.height / 2.0));
final x = (position.dx - boxPosition.dx) / size.width;
final y = (position.dy - boxPosition.dy) / size.height;
return Offset(x, y);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: MouseRegion(
onHover: _updateLocation,
child: Center(
child: SizedBox(
height: 600,
width: 600,
child: GridView.count(
crossAxisCount: 3,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0,
children: List.generate(
9,
(index) {
return DecoratedBox(
key: keys[index],
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
gradient: RadialGradient(
center:
Alignment(_offsets[index].dx, _offsets[index].dy),
radius: 0.66,
colors: const <Color>[
Color(0xFFEEEEEE),
Color(0xFF111133),
],
stops: const <double>[0.0, 1.0],
),
),
);
},
),
),
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment