Open In App

Flutter - Magic 8 Ball App

Last Updated : 13 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
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 using Textbutton in Stateful widgets). For this, we will use Stateless and Stateful Flutter widgets and a Textbutton. 

Steps to build the Magic 8-Ball App in Flutter

Step 1 : Create a new flutter application

Create a new Flutter application using the command Prompt. To create a new app, write the below command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter

Step 2 : Store Images

Download the images below, create an image folder, and add all images to that folder.

Step 3 : Update the pubspec.yaml

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 4 : Working with the main.dart file

Now, add the following code in the main.dart file:

main.dart:

main.dart
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 {
  const Ball({Key? key}) : super(key: key);

  @override
  _BallState createState() => _BallState();
}

class _BallState extends State<Ball> {
  int ballNumber = 1;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextButton(
        onPressed: () {
          setState(() {
            // Random.nextInt(n) returns a 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

The code begins by importing the necessary packages:

  • Flutter’s Material library is used to create the user interface.
  • dart:math package is used for generating random numbers.

Code Overview

Main Function:

  • The main() function initializes the Flutter app by creating an instance of MaterialApp and calling runApp() to start the app.
  • The app's home page is set to BallPage.

BallPage:

  • BallPage is a stateless widget that defines the structure of the main screen.
  • The build() method returns a Scaffold widget that provides the structure of the UI, including:
  • backgroundColor: Set to a light green color.
  • AppBar: A top navigation bar with the title "GeeksforGeeks."
  • body: Contains a Ball widget, which handles the main functionality of the app.

Ball Widget:

  • Ball is a stateful widget, meaning it can change its state during the app's lifecycle.
  • The state is managed by the _BallState class.
  • Within _BallState, an integer variable ballNumber is initialized to 1.

Building the UI:

  • The build() method of _BallState returns a Center widget containing a TextButton.
  • When the TextButton is pressed, the onPressed callback is triggered, which calls setState() to update ballNumber with a random value between 1 and 5.
  • The Image.asset widget displays an image corresponding to the current ballNumber.

Running the App:

When the app is running, it displays a screen with a green background and an AppBar at the top. A ball imagFlutter


Next Article

Similar Reads