Skip to content

Handling network requests.

Valdio Veliu edited this page Mar 29, 2020 · 3 revisions

The general idea of how to handle network requests is to manage all of the API calls in a centralized way. Inside of /config create Api.dart class and all the networking will be handled through this file utilizing the http dart package.

This is just an example of a general way to manage network requests from a single dart class. When you need to make a network requests just access the instance of this class and call the appropriate method you need. Usually, networking gets messy when working on large apps but in my experience, I've observed that generalizing the way you execute these network requests helps in debugging network errors and an overall cleaner code structure.

How easy is it to use this class?

/// ... THIS EASY!
Map response = await Api.get('/endpoint');

The demo app does not actually use this class to make network calls for its data but some comments are left in the code where is the proper place to use this class. We use it to feed data to the redux store through the ViewModel. More on that is explained in the MVVM usage wiki.

The following piece of code is just a part of Api.dart, so look there for more network methods.

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

class Api {
  final host = 'https://host.com';
  final apiVersion = '/api/v1';

  static Api instance = new Api();

  static headers() {
    return {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    };
  }

  static get(route) async {
    String url = _getUrl(route);
    final response = await http.get(url, headers: headers());
    return _parseResponse(response);
  }

  /// ... OTHER NETWORK METHODS

  static _getUrl(route) => "${instance.host}${instance.apiVersion}$route";

  static _parseResponse(response) {
    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON.
      return json.decode(response.body);
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }
}
Clone this wiki locally