Open In App

Flutter – Get District and State Name From Pincode

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

This Flutter application allows users to enter a PIN code and fetch corresponding details such as district, state, and country using the “http://www.postalpincode.in” API. Fetching data from an external API is a common scenario in mobile app development. We’ve employed the http package in Flutter to make HTTP requests seamlessly. Our app communicates with the “Postal PIN Code” API, retrieving location details based on the provided PIN code. In this article, we are going to fetch the pin code details from the API. A sample video is given below to get an idea about what we are going to do in this article.

API Link : http://www.postalpincode.in

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Getting the Necessary Dependencies

Here we have to add the http package dependency to our project.

dependencies:
http: ^1.1.2

Or, Simply we can run the below command in our vs code Terminal.

flutter pub add http

Step 3: Import the Package

First of all import material.dart, http package and dart converter package.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Step 4: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(MyApp());
}


Step 5: Create MyApp Class

In this class we are going to implement the MaterialApp and the Scaffold , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}


Step 6: Create MyHomePage Class

In MyHomePage Class a TextField allows users to input a PIN code, an ElevatedButton triggers the getDataFromPinCode function for fetching data based on the entered code, and a Text widget displays the fetched PIN code details or error messages. The getDataFromPinCode function makes asynchronous HTTP requests to an API, handling various scenarios such as valid or invalid PIN codes and failed API requests. Additionally, the showSnackbar function displays informative messages through a snackbar. Comments are added for better understandings.

// Function to fetch data from API based on the entered PIN code
Future<void> getDataFromPinCode(String pinCode) async {
final url = "http://www.postalpincode.in/api/pincode/$pinCode";

try {
final response = await http.get(Uri.parse(url));

if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);

if (jsonResponse['Status'] == 'Error') {
// Show a snackbar if the PIN code is not valid
showSnackbar(context, "Pin Code is not valid. ");
setState(() {
pinCodeDetails = 'Pin code is not valid.';
});
} else {
// Parse and display details if the PIN code is valid
final postOfficeArray = jsonResponse['PostOffice'] as List;
final obj = postOfficeArray[0];

final district = obj['District'];
final state = obj['State'];
final country = obj['Country'];

setState(() {
pinCodeDetails =
'Details of pin code are:\nDistrict: $district\nState: $state\nCountry: $country';
});
}
} else {
// Show a snackbar if there is an issue fetching data
showSnackbar(context, "Failed to fetch data. Please try again");
setState(() {
pinCodeDetails = 'Failed to fetch data. Please try again.';
});
}
} catch (e) {
// Show a snackbar if an error occurs during the API call
showSnackbar(context, "Error Occurred. Please try again");
setState(() {
pinCodeDetails = 'Error occurred. Please try again.';
});
}
}

Dart




class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  TextEditingController pinCodeController = TextEditingController();
  String pinCodeDetails = "";
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pin Code Details'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Text field for entering the PIN code
            TextField(
              controller: pinCodeController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(labelText: 'Enter Pin Code'),
            ),
            SizedBox(height: 16),
            // Button to trigger fetching data 
            // based on the entered PIN code
            ElevatedButton(
              onPressed: () {
                getDataFromPinCode(pinCodeController.text);
              },
              child: Text('Get Data'),
            ),
            SizedBox(height: 16),
            // Display area for the fetched PIN code details
            Text(pinCodeDetails),
          ],
        ),
      ),
    );
  }
  
  // Function to fetch data from API based on the entered PIN code
  Future<void> getDataFromPinCode(String pinCode) async {
    final url = "http://www.postalpincode.in/api/pincode/$pinCode";
  
    try {
      final response = await http.get(Uri.parse(url));
  
      if (response.statusCode == 200) {
        final jsonResponse = json.decode(response.body);
  
        if (jsonResponse['Status'] == 'Error') {
          // Show a snackbar if the PIN code is not valid
          showSnackbar(context, "Pin Code is not valid. ");
          setState(() {
            pinCodeDetails = 'Pin code is not valid.';
          });
        } else {
          // Parse and display details if the PIN code is valid
          final postOfficeArray = jsonResponse['PostOffice'] as List;
          final obj = postOfficeArray[0];
  
          final district = obj['District'];
          final state = obj['State'];
          final country = obj['Country'];
  
          setState(() {
            pinCodeDetails =
                'Details of pin code are:\nDistrict: $district\nState: $state\nCountry: $country';
          });
        }
      } else {
        // Show a snackbar if there is an issue fetching data
        showSnackbar(context, "Failed to fetch data. Please try again");
        setState(() {
          pinCodeDetails = 'Failed to fetch data. Please try again.';
        });
      }
    } catch (e) {
      // Show a snackbar if an error occurs during the API call
      showSnackbar(context, "Error Occurred. Please try again");
      setState(() {
        pinCodeDetails = 'Error occurred. Please try again.';
      });
    }
  }
  
  // Function to display a snackbar with a specified message
  void showSnackbar(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: Duration(seconds: 2), // Adjust the duration as needed
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  TextEditingController pinCodeController = TextEditingController();
  String pinCodeDetails = "";
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pin Code Details'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Text field for entering the PIN code
            TextField(
              controller: pinCodeController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(labelText: 'Enter Pin Code'),
            ),
            SizedBox(height: 16),
            // Button to trigger fetching data based on the entered PIN code
            ElevatedButton(
              onPressed: () {
                getDataFromPinCode(pinCodeController.text);
              },
              child: Text('Get Data'),
            ),
            SizedBox(height: 16),
            // Display area for the fetched PIN code details
            Text(pinCodeDetails),
          ],
        ),
      ),
    );
  }
  
  // Function to fetch data from API based on the entered PIN code
  Future<void> getDataFromPinCode(String pinCode) async {
    final url = "http://www.postalpincode.in/api/pincode/$pinCode";
  
    try {
      final response = await http.get(Uri.parse(url));
  
      if (response.statusCode == 200) {
        final jsonResponse = json.decode(response.body);
  
        if (jsonResponse['Status'] == 'Error') {
          // Show a snackbar if the PIN code is not valid
          showSnackbar(context, "Pin Code is not valid. ");
          setState(() {
            pinCodeDetails = 'Pin code is not valid.';
          });
        } else {
          // Parse and display details if the PIN code is valid
          final postOfficeArray = jsonResponse['PostOffice'] as List;
          final obj = postOfficeArray[0];
  
          final district = obj['District'];
          final state = obj['State'];
          final country = obj['Country'];
  
          setState(() {
            pinCodeDetails =
                'Details of pin code are:\nDistrict: $district\nState: $state\nCountry: $country';
          });
        }
      } else {
        // Show a snackbar if there is an issue fetching data
        showSnackbar(context, "Failed to fetch data. Please try again");
        setState(() {
          pinCodeDetails = 'Failed to fetch data. Please try again.';
        });
      }
    } catch (e) {
      // Show a snackbar if an error occurs during the API call
      showSnackbar(context, "Error Occurred. Please try again");
      setState(() {
        pinCodeDetails = 'Error occurred. Please try again.';
      });
    }
  }
  
  // Function to display a snackbar with a specified message
  void showSnackbar(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: Duration(seconds: 2), // Adjust the duration as needed
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads