Skip to content

Instantly share code, notes, and snippets.

@creativecreatorormaybenot
Created November 2, 2020 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save creativecreatorormaybenot/8c78cc120237dbf313ed180aca6e0e80 to your computer and use it in GitHub Desktop.
Save creativecreatorormaybenot/8c78cc120237dbf313ed180aca6e0e80 to your computer and use it in GitHub Desktop.
Bouncing Flutter logo deluxe
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
// https://twitter.com/creativemaybeno/status/1323082856898404352?s=20
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: ColoredBox(
color: Colors.black,
child: Center(
child: AspectRatio(
aspectRatio: 16 / 9,
child: const BouncingFlutterLogo(),
),
),
),
),
));
}
class BouncingFlutterLogo extends StatefulWidget {
const BouncingFlutterLogo({Key key}) : super(key: key);
@override
_BouncingFlutterLogoState createState() => _BouncingFlutterLogoState();
}
class _BouncingFlutterLogoState extends State<BouncingFlutterLogo> {
final _logoKey = GlobalKey();
Timer _updateTimer;
@override
void initState() {
super.initState();
_scheduleUpdate();
}
@override
void dispose() {
_updateTimer.cancel();
super.dispose();
}
var _color = Colors.white;
var _x = .0, _y = .0, _dx = 1, _dy = 1;
void _update() {
final availableSize = (context.findRenderObject() as RenderBox).constraints,
logoSize =
(_logoKey.currentContext.findRenderObject() as RenderBox).size;
final previousDx = _dx, previousDy = _dy;
if (availableSize.maxWidth < _x + logoSize.width) {
_dx = -1;
} else if (_x < 0) {
_dx = 1;
}
if (availableSize.maxHeight < _y + logoSize.height) {
_dy = -1;
} else if (_y < 0) {
_dy = 1;
}
if (previousDx != _dx || previousDy != _dy) {
final random = Random();
_color = Color.fromRGBO(random.nextInt(59) + 196,
random.nextInt(59) + 196, random.nextInt(59) + 196, 1);
}
setState(() {
_x += _dx * 15;
_y += _dy * 15;
});
_scheduleUpdate();
}
void _scheduleUpdate() {
_updateTimer = Timer(
// Lock the update rate, no matter the frame rate.
Duration(milliseconds: 74),
_update,
);
}
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: ColoredBox(
color: _color,
child: Stack(
children: [
AnimatedPositioned(
top: _y,
left: _x,
duration: Duration(milliseconds: 74),
child: RotatedBox(
quarterTurns: _dy == 1
? _dx == 1
? 1
: 3
: 0,
child: FlutterLogo(
key: _logoKey,
size: 256,
style: FlutterLogoStyle.stacked,
),
),
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment