Open In App

Flutter – Creating a Simple Pokémon App

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

Preview



Approach

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



Here’s a brief explanation of folder structure:

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:




flutter pub add http

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

Step 3: Import the package

Import HTTP package as




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

Step 4: Create a Stateful Class




// 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




// 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 –




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.


Article Tags :