Flutter Network Request, Decode JSON & Display Image

Almost every mobile app needs to make a network request. Flutter offers an easy to use HTTP library bundled inside the framework so you won’t need to use a third party package. This is also true for encoding, decoding JSON and displaying image from the network. You can clone this project that contains all the example mentioned below.

Network Request & JSON Decoding

An example to make a network request can be looked at api.dart

import 'package:http/http.dart' as http;
import 'dart:io';
import 'dart:convert';
import 'dart:async';

class Api {
    Future<List> getTeams(String leagueName) async {
        final response = await http.get(
            "https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=$leagueName");

        if (response.statusCode == HttpStatus.OK) {
            final jsonResponse = json.decode(response.body);

            if (jsonResponse == null || jsonResponse["teams"] == null)
                return null;

            return jsonResponse["teams"];
        } else {
            return null;
        }
    }
}

To mark a function that will be doing an async operation, we need to mark it with Future<ReturnValue> and async keyword. Also, we need to add await keyword on HTTP operations. Otherwise, those operations will run synchronously and will block the UI thread.
For a JSON operation to decode a string is as simple as calling json.decode, then it will produce a HashMap containing all the JSON keys in String and its values. To access a value, simply use jsonResult[key]. If you want a mapper that convert JSON to object and vice versa, you can use dart package like dson here.

Load Image from Network

To load an image from the network, you can simply use :

Image.network(team.imageURL)

If you’re looking for retrying when fetching image failed, and caching mechanism for the displayed image, you can use flutter_advanced_networkimage