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.


Previous Article
Next Article

Similar Reads

Is Flutter Worth Learning? Top 7 Reasons to Learn Flutter
In today's era, the usage of smartphones has increased exponentially and so has the use of mobile applications and websites. Meanwhile, considering future career prospects, learning web development and mobile app development is strongly recommended for all individuals. And when we come to mobile app development, there are two most-popular open-sour
5 min read
Flutter - Sharing Data Among Flutter Pages
In this article, we are going to find the solution for the problem statement "Import/send data from one page to another in flutter". Before going into the topic, there are some pre-requisites. Pre-requisites:Basics of dart programming language.Setting up Flutter in VS code or Setting up Flutter in Android Studio.Creating first flutter app | Hello W
4 min read
Flutter Quill - Rich Text Editor in Flutter Application
This post will explain how to integrate a rich text editor into your Flutter application so that it may enable rich text editing. There are many more things we can do with Flutter Quill, but they can get a little involved. The example below is a pretty basic demonstration of what we mean. Let's first discuss what flutter quill is and why we need it
5 min read
Flutter - Animated AlertDialog in Flutter
Animating an AlertDialog in Flutter involves using the Flutter animations framework to create custom animations for showing and hiding the dialogue. In this article, we are going to add an animation to an AlertDialog. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.
4 min read
Flutter - Different Types of Loading using Flutter EasyLoading
Flutter applications involve incorporating loading indicators to provide users with feedback during background operations. Flutter has a package for simplifying the process named flutter_easyloading package. This package easiest way to integrate loading indicators with various styles. In this article, we will implement different types of loading in
5 min read
Flutter - Building an Alarm Clock App
Many applications like the Todo app, Exercise App, require alarm clocks to keep track of time in activities. Or if you want to create an alarm clock app for yourself, you will learn this today. If your app contains features like setting the alarm or setting the timer, how you can do this in Flutter? Don’t worry, it's easy with the flutter_alarm_clo
9 min read
How to Choose the Right Architecture Pattern For Your Flutter App?
One of the key decisions you'll make when building a Flutter app is selecting the right architecture pattern. The architecture pattern determines how your app's code is organized and how its different components interact with each other. Choosing the right architecture can make it easier to build, test, and maintain your app over time. In this arti
4 min read
A Hello World App using Flutter
Flutter is an app SDK for building high-performance, high-fidelity apps for iOS, Android, Web(beta), and desktop(technical preview) from a single codebase written in Dart Language. In this article, I will provide line by line explanation of how to build a simple Hello World App using Flutter. In Flutter everything is a Widget and using predefined w
4 min read
Advanced Calculator App using Flutter
Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. In this article, we are going to create an advanced calculator app by using some advanced packages available in Flutter. In this app, you get some functionality. In this app you have only one screen in that screen we perform our whole calcul
4 min read
Simple Calculator App using Flutter
Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. In this article we will build a Simple Calculator App that can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input. Making this app will give you a good revision of flutter
5 min read