Flutter API Calls

 Step 1: first add http package in pubspec.yaml file 

Two Methods: 

1-    Manually type or 

2-    Command     $flutter pub add http

----------------------------------------------------------------------------------

Step 2: Import package into required dart file

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

----------------------------------------------------------      

Step 3: create a function  

API Response

Two Types:

1-Map Type

2- List Type

{
"data": {"id":2,
         "email":"janet.weaver@reqres.in",
         "first_name":"Janet",
        "last_name":"Weaver",
        "avatar":"https://reqres.in/img/faces/2-image.jpg"
        },
"support":{"url":"https://reqres.in/#support-heading",
            "text":"To keep ReqRes free, contributions towards server costs are appreciated!"
          }
}
----------This API response is a map type ------------
  Future apicall() async {
    http.Response response =
        await http.get(Uri.parse("https://reqres.in/api/users?page=2"));
    if (response.statusCode == 200) {
      setState(() {
        stringResponse = response.body; //This response.body is a string type output
        mapresponse = json.decode(stringResponse); //convert string to map
      });
    } else {
      setState(() {
        stringResponse = "Error occured with response code: " +
            response.statusCode.toString();
      });
    }
  }

---------------------------------------------------------------------------------------------------------

Step 4: Call function

  @override
  void initState() {
    apicall();
    super.initState();
  }

--------------------------------------------------------------------------------------------------------

Step 5: Use API response data wherever you want

Text(mapresponse['data']['first_name'].toString()),

----------------------------------------------------------------------------------------------------------

Full Example of Implementation of List View.

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        floatingActionButton: const Icon(
          Icons.offline_bolt,
          size: 50,
        ),
        appBar: AppBar(
          title: const Text("Title"),
        ),
        body: MyHomePage(key: key),
      ),
    );
  }
}

String stringResponse = "";
Map mapresponse = {};

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future apicall() async {
    http.Response response =
        await http.get(Uri.parse("https://reqres.in/api/users?page=2"));
    if (response.statusCode == 200) {
      setState(() {
        stringResponse = response.body;
        mapresponse = json.decode(stringResponse);
      });
    } else {
      setState(() {
        stringResponse = "Error occured with response code: " +
            response.statusCode.toString();
      });
    }
  }

  @override
  void initState() {
    apicall();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: mapresponse['data'].length,
        itemBuilder: (context, index) {
          return Card(
            //  color: const Color.fromARGB(199, 24, 210, 74),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Text(mapresponse['data'][index]['first_name'].toString()),
                Image.network(
                  mapresponse['data'][index]['avatar'],
                  width: 50,
                  height: 50,
                ),
              ],
            ),
          );
        });
  }
}









Comments

Popular posts from this blog

Create table in mysql database in phpmyadmin panel