X
    Categories: Flutter

Flutter HTTP GET Request Tutorial For Beginners

 

Flutter HTTP GET :

Flutter HTTP GET Request method is explained in this part of the tutorial where user can fetch the data and populate the details on to the screen using the network library.

When there is a need to connect our app to server to fetch or post data we use these network library’s to make a smooth and easy data transaction.

In this tutorial on flutter http GET we will fetch the data from a sample api and the parse the information onto our screen as you know we deal with flutter we can use this on both android & iOS apps.

We will be parsing the fields email and body and fetch their respective data and with the help of a model class we populate the data on the screen using TEXT widgets.

As you are aware that in flutter we display data using widgets, its almost a widget based app structure so lets us get started with this tutorial.

Project Structure :

This screen depicts the folder structure of the flutter HTTP GET request method

 

pubspec.yaml :

Add a dependency http and adjust the version accordingly to avoid the code level issues.

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.1

 

Posts.dart :

We need to specify the model class in which we declare the variables id, email, body so that we can parse the data form api

final int id;
final String email;
final String body;

 

Declare the constructor with the parameters

Posts({this.id, this.email, this.body});

 

class Posts {
  final int id;
  final String email;
  final String body;

  Posts({this.id, this.email, this.body});

  factory Posts.fromJson(Map<String, dynamic> json) {
    return Posts(
      id: json['id'],
      email: json['email'],
      body: json['body'],
    );
  }
}

 

Network.dart :

We fetch the data from the api so

https://jsonplaceholder.typicode.com/comments/1

 

Declare async method to fetch the data

Future<Posts> fetchPosts() async {
 
}

 

If response is success will return 200 as status code then we can parse the data

if (response.statusCode == 200) {
  // If the server did return a 200 OK response,
  // then parse the JSON.
  return Posts.fromJson(json.decode(response.body));
}

 

else throw a error stating the reason for the failure

else {
  // If the server did not return a 200 OK response,
  // then throw an exception.
  throw Exception('Failed to load album');
}

 

import 'dart:convert';

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

Future<Posts> fetchPosts() async {
  final response =
  await http.get('https://jsonplaceholder.typicode.com/comments/1');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Posts.fromJson(json.decode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

 

main.dart :

Initialize with void main()

void main() => runApp(MyApp());

 

MyApp class extending StatefulWidget

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

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

 

Declare FutureBuilder in the body and try to observe the data id data is received successfully then display the data on to the screen else provide the error message and until the show a progress indicator such that data is loading.

 

FutureBuilder<Posts>(
    future: fetchPosts(),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        return 
      } else if (snapshot.hasError) {
        return Text("${snapshot.error}");
      }

      // By default, show a loading spinner.
      return CircularProgressIndicator();
    },
  ),

 

On Success display the data as

Padding(
  padding: const EdgeInsets.all(35.0),
  child: Column(
    children: <Widget>[

      Text("Email : "+snapshot.data.email, style: TextStyle(fontSize: 20)),

      Padding(padding: EdgeInsets.all(20)),

      Text("Body : "+snapshot.data.body, style: TextStyle(fontSize: 20)),

    ],
  ),
);

 

flutter http get FullCode :

Providing the full code for flutter http get request method.

import 'package:flutter/material.dart';

import 'Posts.dart';
import 'Network.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Comments',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data With Http Call'),
        ),
        body: FutureBuilder<Posts>(
            future: fetchPosts(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Padding(
                  padding: const EdgeInsets.all(35.0),
                  child: Column(
                    children: <Widget>[

                      Text("Email : "+snapshot.data.email, style: TextStyle(fontSize: 20)),

                      Padding(padding: EdgeInsets.all(20)),

                      Text("Body : "+snapshot.data.body, style: TextStyle(fontSize: 20)),

                    ],
                  ),
                );
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),

      ),
    );
  }
}

 

Flutter http get Output :

This screen depicts the implementation of flutter http get request in your app

 

abhishek:
Related Post

This website uses cookies.