Dart & Flutter: Use of REST GET method

by Aug 16, 2020Mobile Apps

Home 9 Development 9 Mobile Apps 9 Dart & Flutter: Use of REST GET method

This chapter we will continue with the project that we created before. The project could be found on GitHub.

Now when we have a runnable app with homepage and standardized navigation, we can look on how to load data using REST. We will start with the basic example of GET method and, in the next chapter, we will move to a more advance example.

Firstly, we need to allow using an HTTP package. To do that, we have to add one line in pubspec.yaml in the root directory. You can add a newer version if exists (check here).

 http: ^0.12.2

Then we need to allow access for the app to the Internet using uses-permission in AndroidManifest.xml.

 <uses-permission android:name="android.permission.INTERNET" />

Now we can start. Our goal is to download email from this REST API. To process a request, we have to use some new keywords in Dart – Future, async and await.

Future, async & await

The Future is an object that represents a (potential) value, that will be obtained somehow in the future. In other words, this object promise (yes, I used this term because it is very similar construction) to our app that sometimes in the future, there will be an object of this specific type. Which object will be available is specified using structure Future where the T is the type of the object.

Async and await are special constructions (keywords) define how to create and use asynchronous functions. If we want to create an asynchronous function, we have to add async keyword before the function body. In the same way, if we want to call function asynchronously (that is only possible from functions declared as async) we add a keyword await before the function call.

 Future<int> loadData() async {
   return await sleepAndLoadData();
 }

Example

Now, as we know all necessities, we can go directly to our example. We create an async function fetchRESTTestData using Future where T will be a model class using which we store downloaded data.

As you see, the REST call is straightforward. We just use async get function from HTTP package.

 import 'dart:convert' as JSON;
 import 'package:http/http.dart' as http;

 Future<RESTTestData> fetchRESTTestData() async {

   final response =
       await http.get('https://jsonplaceholder.typicode.com/comments/1');

   if (response.statusCode == 200) {
     return RESTTestData.fromJson(JSON.jsonDecode(response.body));
   } else {
     throw Exception('Failed to load album');
   }
 }

 class RESTTestData {
   final int postId;
   final int id;
   final String name;
   final String email;
   final String body;

   RESTTestData({
     this.postId,
     this.id,
     this.name,
     this.email,
     this.body,
   });

   factory RESTTestData.fromJson(Map<String, dynamic> json) {
     return RESTTestData(
       postId: json['postId'],
       id: json['id'],
       name: json['name'],
       email: json['email'],
       body: json['body'],
     );
   }
 }

Then we have to add our new functionality to the UI. We will use our home page that we made earlier for a start. Firstly, we need to obtain data using our function that we just created and store them in a class variable. To achieve that we use function initState on our HomePage. This method is called only once when the state is initialized (in our example, when we open the app or open the home page from the menu).

   @override
   void initState() {
     super.initState();
     futureRESTTestData = fetchRESTTestData();
   }

It is done in the same way as any other element using the Builder class. As we are working with Future object (that hold our REST data), we need to work with FutureBuilder.

             FutureBuilder<RESTTestData>(
               future: futureRESTTestData,
               builder: (context, snapshot) {
                 if (snapshot.hasData) {
                   return Text("Data from REST: " + snapshot.data.email);
                 }
                 return CircularProgressIndicator();
               },
             ),

And that’s all! We can build the app and upload it on our Android device or run it using the emulator. You can see the final result on the emulator picture below.

All related changes described above are on my GitHub.

Recent Articles from the category

BC TechTalk TODAY!

Finally, it is here! Another conference about Business Central is here and due to COVID-19, it's online and totally free. Check all amazing sessions from best speakers from the Business Central world. The agenda is on the web HERE. And if you are interested in mobile...

read more

Dart & Flutter: Project Initialization

We have already prepared development environment and Android Emulators in previous articles. In this chapter, we will look at how to create a new project and on the generated files. To start with, open Visual Studio Code (or any other support development environment)...

read more

Dart & Flutter: What is it?

As from my point of view, the original mobile app for Microsoft Dynamics 365 Business Central is not suitable for some industries, especially when there are some requests on special behaviour (such as automation, bar code scanning & automation or special system...

read more

Sign Up for News

Certifications

Highest certification
Microsoft Data Management and
also in D365 Business Central

Microsoft Certified: Dynamics 365 Business Central Functional Consultant Associate

See other certifications here