Flutter – Magic 8 Ball App
We will be building a Magic 8 Ball app that will give you the answers to all fun tricky questions (basically it is a fun game app that will change its state of image Flatbutton using Stateful widgets). For this, we will use Stateless and Stateful Flutter widgets, a Flatbutton.
We will be using VS Code IDE for this project, you can also use Android Studio or any other IDE. Now, First, create the Flutter project with the initial steps and follow the below steps:
- Step 1: Create an images folder in the project directory and add the required images.
Note: The images used in the article can be download images from here if you want to follow along.
- Step 2: Now, include the images in pubspec.yaml file to use them in the app.
Note: Use proper indentation, otherwise your images will not be included.
- Step 3: Now, add the following code in main.dart file:
Dart
// importing flutter and dart packages import 'package:flutter/material.dart' ; import 'dart:math' ; // Creates a Material App void main() => runApp( MaterialApp( home: BallPage(), ), ); // Creates a Scaffold with // appbar using Stateless widget class BallPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.green[100], appBar: AppBar( backgroundColor: Colors.green[600], title: Text( 'GeeksforGeeks' ), ), body: Ball(), ); } } // Creates a Stateful widget class Ball extends StatefulWidget { Ball({Key key}) : super(key: key); @override _BallState createState() => _BallState(); } class _BallState extends State<Ball> { int ballNumber = 1; @override // Returns app with centered image Flatbutton Widget build(BuildContext context) { return Center( child: FlatButton( onPressed: () { setState(() { // Random.nextInt(n) returns random // integer from 0 to n-1 ballNumber = Random().nextInt(5) + 1; }); }, // Adding images child: Image.asset( 'images/ball$ballNumber.png' ), ), ); } } |
Output: