Flutter Tutorial

flutter http get request with parameters example 2023

flutter http get request with parameters example

Hi, Flutter developer in this, flutter tutorial we are learning how to implement flutter http get request. Like you create an app with flutter and here you need to call the rest API with the get method. So this blog I am making an example using HTTP dependency to call the API and get the response from the API and show data on UI.

How To Use flutter http get request.

Applications often require the POST or GET as well as additional HTTP request.

Flutter comes with the HTTP program that can handle HTTP requests.

Flutter from Google is the Google’s Mobile SDK to build native iOS and Android apps using one codebase. In the process of creating apps using Flutter, developers must move everything is geared towards Widgets which are the building blocks on which the Flutter apps are constructed.

The user interface of the app is comprised of numerous simple widgets each one performing a specific job. This is why Flutter developers often imagine their Flutter app as a tree made of widgets. HTTP package is a Future-based, composable library that makes HTTP requests.

The HTTP Package contains a collection of higher-level functions and classes that allow you to use HTTP resources. It’s multi-platform , and supports desktop, mobile and browser. In this article, we’ll examine “How to install the HTTP Package within Flutter”. For this, follow these steps. We will discuss two ways to accomplish this job.

In this post you will build an example Flutter application that utilizes http as a http package to execute HTTP request to show placeholder data.

For this tutorial to be completed You will require:

This tutorial has been tested using Flutter v1.22.2, Android SDK v30.0.2 along with Android Studio v4.1.

flutter https get request Exanple.

Let’s Start to first create a flutter project and sync successfully. Once the project builds let’s add dependencies in pubspec.ymal file and click on get pub.

Add dependencies

dependencies:
  flutter:
    sdk: flutter
  intl: ^0.18.0
  http: ^0.13.5

Create a Folder With the Name Retrofit Under the Lab Folder.

 in the retrofit, the folder creates a new Dart file name ApiClient and ApiService. In the ApiClient dart file, we are adding the API base URL and API endpoint.

APiService class we just use to create the method of API call and making requests and responses etc.

ApiClient File Code : 

class ApiClient {
  static final String BASE_URL = "https://codeplayon.com/v1/";

  static String getProfiledetails(String id) {
    return BASE_URL + "/users/getUserProfile/${id}";
  }
  
}

ApiService Class Code :

// ignore_for_file: unnecessary_brace_in_string_interps, prefer_interpolation_to_compose_strings, non_constant_identifier_names

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:ev_charging/Utils/SharedPreferenceService.dart';
import 'package:ev_charging/retrofit/APIClient.dart';

class ApiService {

// Get Profile Details
  static Future<http.Response> getProfileDetails(
      String user_id, String token) async {
    return http.get(
      Uri.parse(ApiClient.getProfiledetails(user_id)),
      headers: {
        "Accept": "application/json",
        'Content-type': "application/json",
        'Authorization': token,
      },
    );
  }
}

Now you can call this method on your profile dart file and pass the parameter in API and get a response. you can directly access the get profile method in your main call.

Profile Screen UI and API code.

How do you add query parameters to a Dart http request?

used the below method for the hit the get API call and receive API response on the same class.

Future<dynamic> getProfileDetails() async {
  EasyLoading.show();
  String token = "Bearer "+Prefs.getString(TYPE.S_TOKEN.toString());
  int userid = Prefs.getInt(TYPE.S_USER_ID.toString());
  print("JWT Token: "+token);
  print("ID: "+userid.toString());
  try {
    http.Response response = await ApiService.getProfileDetails(userid.toString(),token);
    if (response.statusCode == 200) {
      EasyLoading.dismiss();
      final jsonData = jsonDecode(response.body);
      print("Response : ${jsonData}");
      setState(() {
        ProfileDetails= ProfileDetailsResponse.fromJson(jsonData);
        Name = ProfileDetails.data[0].name;
        ProfileLink =ProfileDetails.data[0].image_url;
        Mobile = ProfileDetails.data[0].mobile;
      });


    } else {
      EasyLoading.dismiss();
      showToastMessage(SERVER_ERROR_MESSAGE);
    }
  } catch (e) {
    EasyLoading.dismiss();
    print("error ${e.toString()}");

    showToastMessage(e.toString());
    rethrow;
  }
}

Create a New Dart File in your Data Model Class for the API response class ProfileDetailsResponse.

class ProfileDetailsResponse {
  String message;
  bool status;
  List<ProfileDetails> data;
  ProfileDetailsResponse({
    required this.message,
    required this.status,
    required this.data,
  });

  factory ProfileDetailsResponse.fromJson(Map<String, dynamic> json) {
    var datalist = json["data"] as List;
    final message = json["message"];
    final status = json["status"];
    List<ProfileDetails> data =
    datalist.map((e) => ProfileDetails.fromJson(e)).toList();
    print("countries : $datalist");
    return ProfileDetailsResponse(
        message: message, status: status, data: data);
  }

  Map<String, dynamic> toJson() => {
    "message": message,
    "status": status,
    "data": data,
  };
}

class ProfileDetails {
  int id;
  String name;
  String f_Name;
  String m_Name;
  String l_Name;
  String gender;
  String birth_date;
  String email;
  String mobile;
  String address1;
  String address2;
  int PIN;
  String landmark;
  int country_id;
  String image_url;
  int city_id;
  int state_id;




  ProfileDetails({
    required this.id,
    required this.name,
    required this.f_Name,
    required this.m_Name,
    required this.l_Name,
    required this.gender,
    required this.birth_date,
    required this.email,
    required this.mobile,
    required this.address1,
    required this.address2,
    required this.PIN,
    required this.landmark,
    required this.country_id,
    required this.image_url,
    required this. city_id,
    required this. state_id,
  });

  factory ProfileDetails.initial() => ProfileDetails(
    id: 0,
    name: "",
    f_Name: "",
    m_Name: "",
    l_Name: "",
    gender: "",
    birth_date: "",
    email: "",
    mobile: "",
    address1: '',
    address2: '',
    PIN: 0,
    landmark: "",
    country_id: 0,
    image_url: "",
    city_id : 0,
    state_id:0,
  );

  Map<String, dynamic> toJson() {
    return <String, dynamic>{
      'id': id,
      'name': name,
      'f_Name': f_Name,
      'm_Name': m_Name,
      'l_Name': l_Name,
      'gender': gender,
      'birth_date': birth_date,
      'email':email,
      'mobile':mobile,
      'address1':address1,
      'address2':address2,
      'PIN':PIN,
      'landmark':landmark,
      'country_id':country_id,
      'image_url':image_url,
      'city_id':city_id,
      'state_id': state_id,
    };
  }

  factory ProfileDetails.fromJson(Map<String, dynamic> map) {
    return ProfileDetails(
      id: map['id'] ?? 0,
      name: map['name'] ?? "",
      f_Name: map['f_Name'] ?? "",
      m_Name: map['m_Name'] ?? "",
      l_Name: map['l_Name'] ?? "",
      gender: map['gender'] ?? "",
      birth_date: map['birth_date'] ?? "",
      email: map['email'] ?? "",
      mobile: map['mobile'] ?? "",
      address1: map['address1'] ?? "",
      address2: map['address2'] ?? "",
      PIN: map['PIN'] ?? 0,
      landmark: map['landmark'] ?? "",
      country_id: map['country_id'] ?? 0,
      image_url: map['image_url'] ?? "",
      city_id: map['city_id'] ?? 0,
      state_id: map['state_id'] ??0,
    );
  }
}

flutter http get request with parameters example

Profile Screen Complete Code.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:ev_charging/Screens/Custom/BorderBox.dart';
import 'package:ev_charging/Screens/Profile/UserProfileEditView.dart';
import 'package:ev_charging/Screens/SignInWithEmailView.dart';
import 'package:ev_charging/Utils/ConstantsString.dart';
import 'package:ev_charging/Utils/SharedPreferenceService.dart';
import 'package:ev_charging/Utils/constants.dart';
import 'package:ev_charging/Utils/widget_functions.dart';
import 'package:http/http.dart' as http;
import '../../Models/Country.dart';
import '../../Models/ProfileDetailsResponse.dart';
import '../../retrofit/ApiService.dart';

class UserProfileView extends StatefulWidget {
  const UserProfileView({Key? key}) : super(key: key);

  @override
  _UserProfileViewState createState() => _UserProfileViewState();
}

class _UserProfileViewState extends State<UserProfileView> {
  bool isShowPass = false;
  bool isEditModeEnable = false;
  late ProfileDetailsResponse ProfileDetails = ProfileDetailsResponse(message: "", status: false, data: []) ;
  String State_Name="";
  String Countryname="";
  String PinCode="";

  @override
  void initState() {
    Prefs.init();
    getProfileDetails();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
   
    final Size size = MediaQuery.of(context).size;
 
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: Scaffold(
        backgroundColor: COLOR_BACKGROUND,
        body: Container(
          padding: EdgeInsets.fromLTRB(16, 62, 16, 0),
          width: size.width,
          height: size.height,
          // color: COLOR_WHITE,
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  child: Column(children: [
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          BorderBox(
                            child: Icon(Icons.arrow_back_ios_new),
                            width: 44,
                            height: 44,
                            isAction: 1,
                            tabHandler: () {
                              Navigator.of(context).pop();
                            },
                          ),
                          Column(
                            children: [
                              Container(
                                width: 120,
                                height: 120,
                                 child: CircleAvatar(
                                    backgroundImage: NetworkImage((ProfileDetails.data.length>0)? ProfileDetails.data[0].image_url:"")),
                              ),
                              TextButton(
                                onPressed: (() {}),
                                child: Text(
                                  "Add Photo",
                                  style: TextStyle(
                                      color: isEditModeEnable
                                          ? COLOR_GRAY
                                          : COLOR_THEME,
                                      fontWeight: FontWeight.w400,
                                      fontSize: fontsize14),
                                ),
                              ),
                            ],
                          ),
                          Container(
                            child: Column(
                              children: [
                                BorderBox(
                                  child: Icon(
                                    Icons.edit,
                                    color: isEditModeEnable
                                        ? COLOR_GRAY
                                        : COLOR_THEME,
                                  ),
                                  width: 44,
                                  height: 44,
                                  isAction: 1,
                                  tabHandler: () {
                                    Navigator.push(context, MaterialPageRoute(builder: (context) =>  UserProfileEditView(profiledetails:ProfileDetails,CountryList: countryData,State:list))).then((res) => refreshPage());
                                    print("AAAAAAAA");
                                  },
                                ),
                                Text(
                                  "Edit",
                                  style: TextStyle(
                                      color: isEditModeEnable
                                          ? COLOR_GRAY
                                          : COLOR_THEME,
                                      fontWeight: FontWeight.w400,
                                      fontSize: fontsize14),
                                ),
                              ],
                            ),
                          ),
                        ]),
                    TextField(
                      readOnly: true,
                      onChanged: (text) {
                      },
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                          color: Colors.grey, fontWeight: FontWeight.w400, fontSize: fontsize16),
                      controller: TextEditingController(text: (ProfileDetails.data.length>0)? ProfileDetails.data[0].f_Name:""),
                      decoration: InputDecoration(
                        // hintStyle: TextStyle(color: COLOR_THEME),
                        hintText: "First name",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.02),
                    TextField(
                      readOnly: true,
                      onChanged: (text) {},
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                          color: Colors.grey, fontWeight: FontWeight.w400, fontSize: fontsize16),
                      controller: TextEditingController(text: (ProfileDetails.data.length>0)? ProfileDetails.data[0].l_Name:""),
                      decoration: InputDecoration(
                        // hintStyle: TextStyle(color: COLOR_THEME),
                        hintText: "Last name",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.02),
                    TextField(
                      readOnly: true,
                      onChanged: (text) {},
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                          color: Colors.grey, fontWeight: FontWeight.w400, fontSize: fontsize16),
                      controller: TextEditingController(text: (ProfileDetails.data.length>0)? ProfileDetails.data[0].email:""),
                      decoration: InputDecoration(
                        // hintStyle: TextStyle(color: COLOR_THEME),
                        hintText: "Email",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.02),
                    TextField(
                      readOnly: true,
                      onChanged: (text) {},
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                          color: Colors.grey, fontWeight: FontWeight.w400, fontSize: fontsize16),
                      controller: TextEditingController(text: (ProfileDetails.data.length>0)? ProfileDetails.data[0].mobile:""),
                      decoration: InputDecoration(
                        // hintStyle: TextStyle(color: COLOR_THEME),
                        hintText: "Phone",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.02),
                    TextField(
                      readOnly: true,
                      onTap: () {
                        FocusScope.of(context).requestFocus(new FocusNode());
                      },
                      onChanged: (text) {},
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                          color: Colors.grey, fontWeight: FontWeight.w400, fontSize: fontsize16),
                      autocorrect: false,
                      enableSuggestions: false,
                      controller: TextEditingController(text: Countryname),
                      decoration: InputDecoration(
                        // hintStyle: TextStyle(color: COLOR_THEME),
                        hintText: "Country",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        suffixIcon: IconButton(
                          icon: Icon(
                            isShowPass
                                ? Icons.keyboard_arrow_up
                                : Icons.keyboard_arrow_down,
                            color: Colors.grey,
                          ),
                          onPressed: () {
                            setState(() {
                              isShowPass = !isShowPass;
                            });
                          },
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.02),
                    TextField(
                      onTap: () {
                        FocusScope.of(context).requestFocus(new FocusNode());
                      },
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                          color: Colors.grey, fontWeight: FontWeight.w400, fontSize: fontsize16),
                      autocorrect: false,
                      enableSuggestions: false,
                      controller: TextEditingController(text: State_Name),
                      decoration: InputDecoration(
                        // hintStyle: TextStyle(color: COLOR_THEME),
                        hintText: "State",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        suffixIcon: IconButton(
                          icon: Icon(
                            isShowPass
                                ? Icons.keyboard_arrow_up
                                : Icons.keyboard_arrow_down,
                            color: Colors.grey,
                          ),
                          onPressed: () {
                            setState(() {
                              isShowPass = !isShowPass;
                            });
                          },
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.02),
                    TextField(
                      readOnly: true,
                      onChanged: (text) {},
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                          color: Colors.grey, fontWeight: FontWeight.w400, fontSize: fontsize16),
                      controller: TextEditingController(text: (ProfileDetails.data.length>0)? ProfileDetails.data[0].address1:""),
                      decoration: InputDecoration(
                        // hintStyle: TextStyle(color: COLOR_THEME),
                        hintText: "Address",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.02),
                    TextField(
                      readOnly: true,
                      onChanged: (text) {},
                      textAlignVertical: TextAlignVertical.center,
                      style: TextStyle(
                          color: Colors.grey, fontWeight: FontWeight.w400, fontSize: fontsize16),
                      controller: TextEditingController(text: PinCode),
                      decoration: InputDecoration(
                        // hintStyle: TextStyle(color: COLOR_THEME),
                        hintText: "Zip code",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.02),
                    TextButton(
                      onPressed: () {
                        showAlertDialog(context, LOGOUT_MESSAGE, () {
                          Prefs.remove(TYPE.TOKEN.toString());
                          Navigator.pushReplacement(
                            context,
                            MaterialPageRoute(
                              builder: (context) => SignInWithEmailView(),
                            ),
                          );
                        }, ["Cancel", "Confirm"]);
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Log out",
                            style: TextStyle(
                                color: COLOR_RED_TEXT,
                                fontWeight: FontWeight.w500,
                                fontSize: fontsize16),
                          ),
                        ],
                      ),
                      style: ButtonStyle(
                        padding: MaterialStateProperty.all<EdgeInsets>(
                            EdgeInsets.fromLTRB(70, 18, 70, 18)),
                        backgroundColor:
                            MaterialStateProperty.all<Color>(COLOR_LIGHT_GRAY),
                        foregroundColor:
                            MaterialStateProperty.all<Color>(COLOR_RED_TEXT),
                        shape:
                            MaterialStateProperty.all<RoundedRectangleBorder>(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.0),
                          ),
                        ),
                      ),
                    ),
                    addVarticalSpace(size.height * 0.04),
                  ]),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }


  Future<dynamic> getProfileDetails() async {
    EasyLoading.show();
    String token = "Bearer "+Prefs.getString(TYPE.S_TOKEN.toString());
    int userid = Prefs.getInt(TYPE.S_USER_ID.toString());
    print("JWT Token: "+token);
    print("ID: "+userid.toString());
    try {
      http.Response response = await ApiService.getProfileDetails(userid.toString(),token);
      if (response.statusCode == 200) {
        EasyLoading.dismiss();
        final jsonData = jsonDecode(response.body);
        print("Response : ${jsonData}");
       setState(() {
         ProfileDetails= ProfileDetailsResponse.fromJson(jsonData);
         if(ProfileDetails.data[0].PIN==0){
           PinCode = "";
         }else{
           PinCode = ProfileDetails.data[0].PIN.toString();
         }


       });
      
      } else {
        EasyLoading.dismiss();
        showToastMessage(SERVER_ERROR_MESSAGE);
      }
    } catch (e) {
      EasyLoading.dismiss();
      print("error ${e.toString()}");

      showToastMessage(e.toString());
      rethrow;
    }
  }

  refreshPage() {
    getProfileDetails();
  }

}


Read More Tutorial