Data gathering

Let´s start creating the data sources clients. Create a new folder called data inside lib directory. Next step is creating contact_data.dart file inside data folder.

In this file the Contact class and the interface that will expose how to get contacts and also an exception that will notice in case anything went wrong during the data fetch will be defined.

So, the contacts list should be place in another file as a mock implementation.

Check the result:

As it was said, this file contains the Contact class, ContactRepository interface defining a fetch method which returns a Future<ContactList> and FetchDataException.

In order to use Future dart:async must be imported, Future allows working using promises in Dart. An example about this is below in this post.

Mock Repository

Our first ContactRepository interface implementation will be a mocked one. Create another file called contact_data_mock.dart inside data folder. In this file a class that implements ContactRepository interface and that returns the contacts list from the last post through the fetch method will be created.

Import both dart:async and contact_data.dart in order to use Future. ContactRepository and Contact.

As seen, a class to implement ContactRepository is created and inside the fetch method a contact list is returned using a Future.

Random User Repository

Its second implementation will be using RandomUser service, this will cover how to fetch data calling a service using Dart.

Inside data folder, create a file called contact_data_impl.dart and add the following code.

In this case, the class implementing ContactRepository interface is RandomUserRepository.

Inside the fetch method, execute a get function to query an URL contained inside _kRandomUserUrl. In order to do this, first import package:flutter/http.dart. Using as operator makes the http variable containing the whole package.

In order to perform the query, use http´s get method. It returns a Future which is Dart´s way of using promises. Future´s then method should be called when the query is finished and all the information was already gathered.

The then method takes a lambda as a parameter in order to notify the reply. It returns body and a statusCode to check if everything is OK, otherwise FetchDataException will be thrown.

Last step is reading a Json, to do so, use dart:convert and JsonDecoder class which takes reply´s body as a parameter.

Let´s check how a Random User Json reply is:

Inside results, you can iterate every element using a Map and turn them into Contact and return the list using toList method.

To do so, a new Contact constructor that allows to create contacts from a Json must be defined.

In this constructor fullName and email attributes are extracted from map and assign by name.