Blog Details

img
Development

HTTP GET Response in Flutter

Spoke Right / 31 Oct, 2023

There is no use of building a UI in Flutter until you Integrate it with your backend. A GET request is used to extract useful data from your backend to use it in your application. To perform a GET request in Flutter we need to follow 3 steps –

  1. Get the latest dart Http package.
  2. Enter the package in pubspec.yaml file in your dependencies section.
  3. Import the package in your main.dart file.

In the URL part, you can enter your backend Rest API link.

NOTE:

  • You can also divide the main.dart file in various sections but for simplicity, it is being performed only in one file.
  • A random JSON GET request URL from the Internet has been used here, which can be replaced with any backend Restful API.

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(

      home: HomePage(),

    );

  }

}


//Creating a class user to store the data;

class User {

  final int id;

  final int userId;

  final String title;

  final String body;


  User({

    this.id,

    this.userId,

    this.title,

    this.body,

  });

}


class HomePage extends StatefulWidget {

  @override

  _HomePageState createState() => _HomePageState();

}


class _HomePageState extends State {

//Applying get request.


  Future> getRequest() async {

    //replace your restFull API here.

    String url = "https://jsonplaceholder.typicode.com/posts";

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


    var responseData = json.decode(response.body);


    //Creating a list to store input data;

    List users = [];

    for (var singleUser in responseData) {

      User user = User(

          id: singleUser["id"],

          userId: singleUser["userId"],

          title: singleUser["title"],

          body: singleUser["body"]);


      //Adding user to the list.

      users.add(user);

    }

    return users;

  }


  @override

  Widget build(BuildContext context) {

    return SafeArea(

      child: Scaffold(

        appBar: AppBar(

          title: Text("Http Get Request."),

          leading: Icon(

            Icons.get_app,

          ),

        ),

        body: Container(

          padding: EdgeInsets.all(16.0),

          child: FutureBuilder(

            future: getRequest(),

            builder: (BuildContext ctx, AsyncSnapshot snapshot) {

              if (snapshot.data == null) {

                return Container(

                  child: Center(

                    child: CircularProgressIndicator(),

                  ),

                );

              } else {

                return ListView.builder(

                  itemCount: snapshot.data.length,

                  itemBuilder: (ctx, index) => ListTile(

                    title: Text(snapshot.data[index].title),

                    subtitle: Text(snapshot.data[index].body),

                    contentPadding: EdgeInsets.only(bottom: 20.0),

                  ),

                );

              }

            },

          ),

        ),

      ),

    );

  }

}

0 comments

Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so (/usr/local/lib/php/extensions/no-debug-non-zts-20210902/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0