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('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, 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.

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 =
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 conversation.so 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 .

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 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

Share this post: on Google+

您可能感兴趣的

Top 5 REST API Security Guidelines When developing REST API, one must pay attention to security aspects from the beginning. In this post I will review and explain top 5 security guidel...
安装使用RESTful 框架SLIM笔记 RESTful API框架有很多,其他语言不熟悉,我就找了PHP的。由于SLIM的 有中文文档 ,阅读起来速度快许多,加之 这篇文章 里有非常易懂的示例,于是选了 SLIM 。 相关框架: http://www.golaravel.com 是一...
19- vue django restful framework 打造生鲜超市 -支付宝支付源码解读... Django2.0.2(Django-rest-framework)以及前端vue开发的前后端分离的商城网站 线上演示地址: http://vueshop.mtianyan.cn/ github源代码地址: https://github.com/mtianyan/VueDjangoFr...
6- vue django restful framework 打造生鲜超市 -完成商品列表页(下)... drf中的request和response drf对于django的request和response进行了一层封装。 浏览器请求的request会被drf进行一定的封装,扩展了标准的http request REST framework's Request class extends t...
How to create REST APIs using aiohttp aiohttp is HTTP client/server for python and AsyncIO . It supports both server websockets and client websockets. As it works asynchronously, it can h...
责编内容来自:Android Development (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » Calling REST API from a Flutter App



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

使用声明 | 英豪名录