Skip to content

Instantly share code, notes, and snippets.

@royarg02
Last active November 2, 2020 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save royarg02/1d6c3af41b161e467d5dd25096dbfeba to your computer and use it in GitHub Desktop.
Save royarg02/1d6c3af41b161e467d5dd25096dbfeba to your computer and use it in GitHub Desktop.
A dice roller app built with Flutter.
import 'dart:math' as math;
import 'package:flutter/material.dart';
var r = math.Random(412);
void main() {
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Dice Roller',
home: Scaffold(
appBar: AppBar(
title: Text('Dice Roller'),
backgroundColor: Colors.amber,
),
body: Body(),
),
);
}
}
class Body extends StatefulWidget {
@override
_BodyState createState() {
return _BodyState();
}
}
class _BodyState extends State<Body> {
int _dice = 0;
String determineImage(int value) {
switch (value) {
case 1:
return './assets/dice_1.png';
case 2:
return './assets/dice_2.png';
case 3:
return './assets/dice_3.png';
case 4:
return './assets/dice_4.png';
case 5:
return './assets/dice_5.png';
case 6:
return './assets/dice_6.png';
default:
return './assets/empty_dice.png';
}
}
void _rollDice() {
const _snackBar = SnackBar(
content: Text('Rolling...'),
duration: Duration(milliseconds: 300),
);
setState(() {
_dice = r.nextInt(6) + 1;
});
Scaffold.of(context).showSnackBar(_snackBar);
}
void _countUp() {
setState(() {
_dice = _dice < 6 ? _dice + 1 : _dice;
});
}
void _resetDice() {
setState(() {
_dice = 0;
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
determineImage(_dice),
height: 300,
width: 300,
),
ElevatedButton(
child: Text('ROLL'),
onPressed: _rollDice,
),
ElevatedButton(
child: Text('COUNT UP'),
onPressed: _countUp,
),
ElevatedButton(
child: Text('RESET'),
onPressed: _resetDice,
),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment