Building Flutter applications whose content is static can be a bad idea. Instead, you should consider building applications that can fetch content from the Web server.

In this tutorial, I’m going to show you how to use the classes and methods available in the Flutter SDK to connect to remote web servers and interact with them using their REST APIs.

Calling REST API from a Flutter App

Creating an HTTP Connection


To create an HTTP Client we need to add an import.

import 'dart:io';

The following code snippet shows you how to setup a connection with the GitHub API endpoint:

_getUserApi() async {
  var httpClient = new HttpClient();
  var uri = new Uri.https('api.github.com', '/users/1');
  var request = await httpClient.getUrl(uri);
  var response = await request.close();
  var responseBody = await response.transform(UTF8.decoder).join();
  return responseBody;
}

Note that the HTTP APIs use Dart Futures in the return values.Flutter recommend using the API calls with the async/await syntax.

Responsive UI


Network calls are slow. It doesn’t matter where you are on your phone. Sometimes, your server might be slow and you just don’t want to show a white page. So you want to show a progress bar. There is a great library called async_loader. Following code snippet show how to use it.

Usage

To use this plugin, add async_loader as a dependency in your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  async_loader: "^0.1.1"

Create instance

final GlobalKey<AsyncLoaderState> _asyncLoaderState =
new GlobalKey<AsyncLoaderState>();

var _asyncLoader = new AsyncLoader(
  key: _asyncLoaderState,
  initState: () async => await _getUserApi(),
  renderLoad: () => new CircularProgressIndicator(),
  renderError: ([error]) =>
  new Text('Sorry, there was an error loading'),
  renderSuccess: ({data}) => new MyHomePage(data),
);

You need to create an async loader in your build function.It has a few parameters.It has initState,renderLoad,renderError,and renderSuccess.

initState is basically as the widget is floating, what do you want to load?what data do you want to load?

renderLoad is as it’s being loaded, what do you want to show? So in renderLoad, I show a progress bar.

renderError is if something went crazy wrong, what do you want to do? So here for the sake of the demo, I just have new text error loading conversation.

renderSuccess is called with your data that you return in your initState. And then you can take that data, and then you can actually render your entire UI.

JSON Parsing


In Android, you can use GSON for JSON parsing.There’s nothing like this on Flutter, mainly because Flutter doesn’t have a reflection.There is a great library called json_serializable.

Setting up json_serializable

To include json_serializable, you need one regular and two dev dependencies. dev dependencies are dependencies that are not included in your app source code.

Check the latest versions.

pubspec.yaml

dependencies:
  # Your other regular dependencies here
  json_annotation: ^0.2.2

dev_dependencies:
  # Your other dev_dependencies here
  build_runner: ^0.7.6
  json_serializable: ^0.3.2

Click “Packages Get” in your editor to make these new dependencies available in your project.

Convert  User class to a json_serializable .

user.dart

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';


@JsonSerializable()

class User extends Object with _$UserSerializerMixin {

  User(this.id,this.name, this.location);

  int id;
  String name;
  String location;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}

When creating json_serializable classes the first time, you will get errors.Because the generated code for the model class does not exist yet. To resolve this, you must run the code generator that generates the serialization boilerplate for us.

By running (in command prompt)flutter packages pub run build_runner build in our project root, you can generate json serialization code for our models whenever needed.

Consuming json_serializable models

To deserialize a JSON string json_serializable way, we do not have actually to make any changes to our previous code.

Map userMap = JSON.decode(_response);
_user = new User.fromJson(userMap);
Same goes for serialization. The calling API is the same as before.
String json = JSON.encode(_user);
print(json);

Download Project from GitHub