Open In App

Flutter – Magic 8 Ball App

Last Updated : 02 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

Explanation of main.dart

  1. The code starts by importing the necessary packages.
  2. The Material design library is used to create a user interface, and the dart:math package is used for basic mathematical operations.
  3. The main() function creates an instance of the Material app and calls runApp() to start it running.
  4. This app has two pages: BallPage and FlatButtonPage.
  5. BallPage contains a body widget that contains a ball object.
  6. The build() method returns a Scaffold widget with the following properties: backgroundColor set to green, title set to “GeeksforGeeks”, and child widgets for displaying the ball number and an image asset for showing the ball onscreen.
  7. FlatButtonPage contains only one child widget, which is a FlatButton widget with two properties: onPressed property that sets state when it’s pressed, and child property that references BallPage .
  8. When FlatButton Page is pressed, its onPressed() method will be called, which will call BallPage ‘s setState() method to update ballNumber .
  9. Finally, when FlatButton Page is released from touch or keyboard input, its child’s destroy() method will be called so that BallPage can release any resources it needs.
  10. The code first imports the necessary packages for Flutter and Dart.
  11. Next, it creates a Material App with two Scaffolds – one for the Home Page and another for the Ball Page.
  12. The Home Page has a FlatButton that will be triggered when it is pressed.
  13. The Ball Page contains an Image as well as a child FlatButton that will be triggered when the ballNumber variable is incremented by 1.
  14. Finally, the _BallState class extends StatelessWidget which creates and manages the state of the Ball widget.
  15. When the app is run, you should see a green background with a green AppBar on top and a centered ball image in the center of each screen.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads