Journey to the Flutter Network World

Veli Bacık
Jan 17 · 8 min read

Many application most important point network process. We will learn how to manage this and talk about vexana package.

Image for post
Image for post

If you write grow mobile application, perhaps be careful point network layer because it’s consuming your network traffic and handle critical exception scenario.

Your network layer to contact service and works to fetch response model for request model. Your request has these important points:

  • Query: It’s mean added key value in your request URL.(if your query first, a question mark will add to the end)
    Ex: https://twitter.com/home?lang=tr
  • Header: It has your key, token, identity no or service property.
Image for post
Image for post
Postman
  • Body: It includes your request model and service parse this. If you have more query or important data, should add request body.
Image for post
Image for post
Postman

Finally of course response. The response is very important for client application if don't it right control response model, your app will possibly crash.

Let’s talk what we do for flutter project.

Flutter has more packages to control network traffic. These are packages most used:

  • http_ : It’s very useful and simple managed network requests and written for dart dev teams.
import 'package:http/http.dart' as http;

var url = 'https://example.com/whatsit/create';
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
Response response = await Dio().get("http://www.google.com");
print(response);

Dio ready to use more features for example interceptors, cookie manager, error, form data, http2 support etc so I use more dio for these features.

Every package has a similar error, the package doesn’t support dynamic model response, it’s very important to point so should be able to want the response model return back your hand.

Image for post
Image for post
https://jsonplaceholder.typicode.com/comments?postId=2

Generally, the mobile application has one service point(without dev, prod type) and another property is the standard first time. We create a network manager class and we will manage through this instance.

What do we need?

Okay, dio or HTTP works for network request but it doesn’t enough. I want to response&request model must be a generic type because It’s could be always different type. How we use this generic type, let’s do it together.

You use flutter&dart project, could be seen “toJson,fromJson”. These functions give the ability to JSON decode and encode when added any class.

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},

I most use JSON serializable library but if I use to first time, I use JSON to dart website for creating the model.

And we can create this class for JSON.

We see this JSON class is formed fromJson and toJson method so we should know, every data class need these functions. I create INetworkModel therefore and I want to sure any model must contain these functions.

It’s very short but it will be very useful for us because we need limited request functions just has these methods. Dart has not to embed reflection so we don’t create any instance at run time so the user should give a generic model from this INetworkModel.

Actually, you want so much reflection, you can look mirror package. It’s work mirror but work with build runner package so you declare annotation any class and build runner create .g file containing this reflection ability. I was creating an article on this topic.

Okay let’s make an example with INetworkModel:

Everything okay, we will see later what will work our features.

It’s created the main goal to manage network request and return back user hand generic response. I see too many projects so created this constructor and I want to require functions and create this for required.

I used diomix because it has more options. I just added my idea and combined mixin with this.

class NetworkManager with DioMixin implements Dio, INetworkManager
{...}

I required some property to use my network operations.

So we know now:

  • Options: User defines service attributes in options. (like a base URL, network headers etc.)
  • Interceptor: If you want to write middleware on request, response and error scopes, here you can write custom business.
  • OnRefreshToken & OnRefreshFail: Many applications have any authorization solutions(for example jwt) so your application could get error Unauthorized. I fixed this very easy. OnRefreshToken work to network response has thrown 401 the other is what to do at error time (for example, log out the app or show to alert)
  • File Manager: I create caching options with my solutions so it’s needed which one will you use. Now, only support File and Shared options(i will add SQLite support coming soon).
  • Error Model: Your service layer returns always the same error model when defining an error model to receive this model.
Image for post
Image for post
https://httpstatusdogs.com/401-unauthorized

Network adventure going very well, let’s write the fetch function and will do it request-response operations.

We think now. Request type&model, Response type, base Url, Cache Type(if it is available), logger etc in your hand for our constructor so time to use all. We will manage post, put, delete and get request and return whatever you want a response. Let’s try:

There it is. This function has behind that huge request-response. This function doing everything but okay how do it?

  • This method need request model must be extended INetworkModel so I want to must generic T type deriving base network model for to JSON from JSON options.
  • R ? R type is return user whatever response. I didn’t do it on purpose R type so R sometimes is List<T>, sometimes just T and sometimes just primitive Type Int, Double etc.
  • User must say request type and which use the model for parsing.
  • UrlSuffix needs sometimes for like “user/1”.
  • The expiration time for cache operations.
  • I don't use cancel token, onReceivePgress now. I will have to do next time.

So, I use this parameter and send to request for a client with base options. I’m looking client have any cache data before request. Its functions return data when a client has cache.

If you want cache detail, can read this article and look cache operation file.

Then I send to request and looking just status code 200 (success codes can be increased this here.). This least three situation right here:

  • Everything is done and will parse its data.
  • Everything is done but the server will be sending specific status like a 203 or 303, these handle and operations switch scope.
  • Some client has specific error or server send example internal server(500) error, these situations send to error scope.

Let’s continue. A time comes for parse when the request is done. Let’s remember, we talked INetworkModel and add ToJson, FromJson ability to any class. It will be very useful for us this here.

It's too little but very useful.

  • First, check if the server sends list response, these functions mapped list and return List<R> type.

Example : (Todo T, List<Todo> R ) json_place_holder_test in vexana

final response = await networkManager.fetch<Todo, List<Todo>>("/todos", parseModel: Todo(), method: RequestType.GET);
  • If response single JSON, it mapped to a single object.

Example : (BasicUser T, BasicUser R ) custom_api_test in vexana

final response = await networkManager.fetch<BasicUser, BasicUser>("/user", queryParameters: {"isOk": 2}, parseModel: BasicUser(), method: RequestType.GET);
  • Last check if not response list or JSON, it means primitive type so this write server response value in name property from the empty model.

Example : (Todo EmptyModel, EmptyModel R ) http_dog_test in vexana

final response = await networkManager.fetch<EmptyModel, EmptyModel>("/dogs/0/code.json", parseModel: EmptyModel(), method: RequestType.GET);

Response writes to the cache when user definitions duration parameter in its. Cache it’s very important to the app. I write to the cache for this like here.

That’s checked first duration param then it’s there must need file manager defined to NetworkManager class if not defined here, will to return an exception.

This method converts any object to string values and writes cache with the file manager. (only support file JSON and shared layer)

Image for post
Image for post
https://github.com/VB10/vexana/tree/master/lib/src/cache

The other important point fetching local cache data. It will check like the above methods. It if has any data, will return from the client and it has a remove all cache methods when used for user logout the app or any other situation.

We completed to core operations. You create a network manager instance from INetworkManager and define core property in its. After creating any model from INetworkModel. Everything it’s your hand, call you any request wit vexana.

Let’s look at this how to use vexana:

Image for post
Image for post
JSON place holder test

If you want to more details, look example folder and test layer.

Image for post
Image for post
Vexana Test

This extension will help yours every time. You will need always a path, sometimes create the static path or classpath for this. I create network path enum and write the extension for this so I have all paths as enum value.

Example for Network Path Extension

await networkManager.fetch<BasicUser, BasicUser>(NetworkPath.LOGIN.rawValue,queryParameters: {"isOk": 1}, parseModel: BasicUser(), method: RequestType.GET);

Finally, everything is done ☘️

This adventure will give you an idea and how you will do the operations in your own projects so everything will be in your hand.

Cheers for reading.
Always happy coding ☘️

Follow Flutter Community on Twitter: https://www.twitter.com/FlutterComm

Flutter Community

Articles and Stories from the Flutter Community

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store