Service Call in Flutter with Retry Button, Catch Network failures.

By | December 21, 2018

Hello Devs,

In today’s tutorial we will find out how we can write a simple service call in flutter and show retry when network call fails.

Below is a sample video of the app we are going to make…

Watch Video Tutorial

You can watch the complete video tutorial from here…

Add Library

To do service calls in Flutter, you need to add ‘http’ library. For that open ‘pubspec.yaml‘ which is preset in the root of your folder.

Now you have to add the library from this here.

So our ‘pubspec.yaml‘ file should look like this.

name: flutter_demo1
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.0.0-dev.68.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  http: "0.11.3+17"

dev_dependencies:
  flutter_test:
    sdk: flutter

Service Call

I am using the below sample fake json url for getting the data.

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

Here is the sample output

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Our Service call function will look like this.

void callService() async {
    try {
      final response =
          await http.get("https://jsonplaceholder.typicode.com/todos/1");
      if (response.statusCode == 200) {
        print(response.body);
        final parsed = json.decode(response.body);
        print(parsed["id"]);
      } else {
        print("Error");
      }
    } catch (e) {
    }
  }

Complete Example

We have a text and a button in the UI. The button will invoke the above service call and we will show the results in the Text Widget.

We will show a CircularProgressBar when the service is loading and hides when complete. If the service fails, we will show the error in the Text Widget.

Our complete program will look like this.

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  String title = 'No Data';
  bool isLoading = false;

  void callService() async {
    setState(() {
      isLoading = true;
    });
    print("Calling Service...");

    try {
      final response =
          await http.get("https://jsonplaceholder.typicode.com/todos/1");
      if (response.statusCode == 200) {
        print(response.body);
        final parsed = json.decode(response.body);
        print(parsed["id"]);
        print(parsed["title"]);
        setState(() {
          title = parsed["title"];
        });
      } else {
        print("Error");
        setState(() {
          title = "Error Occurred";
        });
      }
    } catch (e) {
      setState(() {
        title = e.toString();
      });
    }

    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            isLoading
                ? CircularProgressIndicator()
                : Text(
                    title,
                  ),
            RaisedButton(
              child: Text("Call Service"),
              onPressed: callService,
            )
          ],
        ),
      ),
    );
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *