Calling REST API from a Flutter App

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. That might sound hard, but Web server exposing their resources through REST APIs, it’s actually quite easy.

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.

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('', '/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, it will just be slow.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.The way you do that currently in Flutter is you have a show loading equals false.If show loading is false in your building function, you show a spinner animation else ,you show your entire widget tree.Now, I didn’t want to write that over and over again, so I started finding a solution for it and so what I came across was this great library called async_loader .Following code snippet show how to use it.


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

    sdk: flutter
  async_loader: "^0.1.1"

Create instance

final GlobalKey _asyncLoaderState =
new GlobalKey();
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? As 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 you see a boring old error loading conversation on the page.what you typically want is some sort of nice little graphic that says, oh, something went wrong please press back.and then finally when all your data is loaded, 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 that I found, mainly because Flutter doesn’t have reflection .I’m a lazy developer. I did not want to write down all these single data types over and over again and build out a fromJSON and to map .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 .


  # Your other regular dependencies here
  json_annotation: ^0.2.2
  # 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 .


import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
class User extends Object with _$UserSerializerMixin {
  User(,, this.location);
  int id;
  String name;
  String location;
  factory User.fromJson(Map 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);

Download Project from GitHub

Share this post: on Google+

稿源:Android Development (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Calling REST API from a Flutter App

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录