Skip to content
Related Articles

Related Articles

Flutter – Magic 8 Ball App

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 15 Jan, 2021

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:


// importing flutter and dart packages
import 'package:flutter/material.dart';
import 'dart:math';
// Creates a Material App
void main() => runApp(
        home: BallPage(),
// Creates a Scaffold with
// appbar using Stateless widget 
class BallPage extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeeksforGeeks'),
      body: Ball(),
// Creates a Stateful widget 
class Ball extends StatefulWidget {
  Ball({Key key}) : super(key: key);
  _BallState createState() => _BallState();
class _BallState extends State<Ball> {
  int ballNumber = 1;
  // 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'),


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!