Open In App

Flutter – Creating a Simple Pokémon App

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Embark on an exciting journey into the vibrant world of Pokémon with an innovative mobile app, that we will be building in this article – ‘PokeDex.’ Powered by the versatile Flutter framework and integrated with the extensive Pokemon API, this app redefines the Pokémon experience. Flutter is a cutting-edge open-source UI framework developed by Google, that empowers us to craft seamless, visually appealing applications across mobile, web, and desktop platforms, all from a unified codebase.

Features of Application

  • Comprehensive Pokémon Database: Explore an extensive collection of Pokémon characters, each meticulously detailed with their names, captivating images, and valuable candy information.
  • Intuitive User Interface: Dive into an intuitive and user-friendly interface designed to enhance exploration of the Pokémon universe. Effortlessly navigate through the app and discover a world of Pokémon at your fingertips.
  • Real-time Data Fetching: Stay up-to-date with the latest Pokémon information thanks to real-time data fetching capabilities. Experience the thrill of discovering new Pokémon and their unique traits as soon as they are available.
  • Seamless Cross-Platform Compatibility: It’s a single codebase application that serves on mobile devices, desktops, or web browsers, and ensures a consistent and immersive experience.

Preview

Screenshot-(78)

Approach

  • We will create a StatefulWidget to manage state, specifically the pokeData and pokeList variables.
  • In next step we would complete the getData method to fetch Pokémon data from the API.
  • Once the data is successfully fetched and stored, the UI in the body of the Scaffold widget would be updated to display the Pokémon information, such as names, images, and other details, using ListView widget.

Step By Step Implementation

Step 1: Create a New Project in Visual Studio Code or Android Studio.

In this article, we will be using Visual Studio Code Editor to build our app. Then run below command to create Flutter project

flutter create PokeDex

The folder structure will be as follows

flutter-folder-structure

Here’s a brief explanation of folder structure:

  • android/ and ios/: These folders contain platform-specific code for Android and iOS. There is no need to modify these unless there are specific platform requirements.
  • lib/: This is where the main Dart code for our app resides. The main.dart file is the entry point of app.
  • test/: This folder is used for writing tests for application.
  • pubspec.yaml: This is the configuration file for Flutter app. All dependencies, assets, and other project settings are defined here.

Step 2: Add the Package in the pubspec.yaml File

Now we need to add the package into the pubspec.yaml file. From the command line:

Dart




flutter pub add http


This will add “http” package under dependencies section in pubspec.yaml file as shown below:

Screenshot-(79)

Step 3: Import the package

Import HTTP package as

Dart




import 'package:http/http.dart' as http;


Step 4: Create a Stateful Class

Dart




// MyApp class, which represents the 
// main application widget.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // MaterialApp widget configures 
    // the overall app structure.
    return MaterialApp(
      // Hide debug banner in the app
      debugShowCheckedModeBanner: false
      // Set the home page of 
      // the app to MyHomePage widget
      home: MyHomePage(), 
    );
  }
}
  
// MyHomePage class, a StatefulWidget 
// representing the main screen of the app.
class MyHomePage extends StatefulWidget {
  // Create state for the widget
  @override
  _MyHomePageState createState() => _MyHomePageState(); 
}
  
// _MyHomePageState class, the state for MyHomePage widget.
class _MyHomePageState extends State<MyHomePage> {
  // Variables to store Pokemon data retrieved from the API.
    
  // Map to store Pokemon data
  Map pokeData = {}; 
    
  // List to store the list of Pokemon
  List pokeList = []; 
  
  // initState method, called when the 
  // stateful widget is inserted into the tree.
  @override
  void initState() {
    // Call the superclass's 
    // initState method.
    super.initState(); 
    // Any initialization code for the state goes here.
  }
  
  // build method, responsible for
  // building the UI of the widget.
  @override
  Widget build(BuildContext context) {
    // Scaffold widget provides a basic
    // material design visual structure.
    return Scaffold(
      // Set background color of the app.
      backgroundColor: Colors.white, 
      appBar: AppBar(
        // App bar with the title "PokeDex".
        title: Text("PokeDex"), 
        // Set app bar background color to green.
        backgroundColor: Colors.green, 
      ),
      // Display "Wait" text at the center of the screen.
      body: Center(child: Text("Wait")),
    );
  }
}


Step 5: Call API to get Pokemon Data

Dart




// This function is responsible for fetching data 
// from a Pokémon API and processing the response.
Future<void> getData() async {
  // Declare a variable to store 
  // the HTTP response from the API.
  http.Response pokeResponse;
  
  // Define the URL of the Pokémon API as a string.
  String urlString =
  
  // Parse the URL string into a Uri 
  // object for making the HTTP request.
  Uri uri = Uri.parse(urlString);
  
  // Perform an asynchronous HTTP GET request 
  // to fetch data from the specified URL.
  pokeResponse = await http.get(uri);
  
  // Check if the HTTP response status code is 200,
  // indicating a successful request.
  if (pokeResponse.statusCode == 200) {
    // If the response status code is 200, parse 
    // the JSON data from the response body.
    pokeData = json.decode(pokeResponse.body);
      
    // Extract the 'pokemon' list from the parsed 
    // JSON data and assign it to the 'pokeList' variable.
    pokeList = pokeData['pokemon'];
  } else {
    // If the response status code is not 200, throw an
    // exception indicating the failure to load data.
    throw Exception('Failed to load data from the API');
  }
}


Complete Code

Now, let’s dive into the complete code for Pokémon app. When Flutter app is created, main.dart is already present in its folder. In main.dart file, write the following code –

Dart




import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:core';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  Map pokeData = {};
  
  List pokeList = [];
  
  Future<void> getData() async {
    http.Response pokeResponse;
    String urlString =
    Uri uri = Uri.parse(urlString);
  
    pokeResponse = await http.get(uri);
  
    if (pokeResponse.statusCode == 200) {
      pokeData = json.decode(pokeResponse.body);
      pokeList = pokeData['pokemon'];
    } else {
      throw Exception('Failed to load data from the API');
    }
  }
  
  void initState() {
    getData();
    super.initState();
  }
  
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text("PokeDex"),
          backgroundColor: Colors.green,
        ),
        body: pokeList == null
            ? Center(child: Text("Wait"))
            : ListView.builder(
                itemCount: pokeList == null ? 0 : pokeList.length,
                itemBuilder: (context, index) {
                  return Container(
                    child: Column(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Container(
                            height: 300,
                            width: 300,
                            decoration: BoxDecoration(
                                color: Colors.green,
                                borderRadius: BorderRadius.circular(20)),
                            child: Column(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text(
                                    pokeList[index]['name'],
                                    style: TextStyle(
                                        fontSize: 20,
                                        fontWeight: FontWeight.w600,
                                        color: Colors.white),
                                  ),
                                ),
                                Image.network(
                                  pokeList[index]['img'],
                                  width: 300,
                                  height: 200,
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      "Candy: ",
                                      style: TextStyle(
                                          fontSize: 15,
                                          fontWeight: FontWeight.w500,
                                          color: Colors.white),
                                    ),
                                    Text(pokeList[index]['candy'],
                                        style: TextStyle(
                                            fontSize: 15,
                                            color: Colors.white,
                                            fontWeight: FontWeight.w500)),
                                  ],
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  );
                },
              ));
  }
}


Output:

Conclusion

This code creates a simple Pokémon app that displays Pokémon characters with their names, images, and candy information. It’s a great starting point for building flutter applications, and can be further customised as per requirements.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads