API Integration in Flutter with JSON Parsing using HTTP Package , where HTTP Package is the most basic and most used package in Flutter.
Read about some of our Flutter app development services
What is API?
API stands for Application Programming Interface.
API is the one which can be viewed as a set of rules and tools which are used to design various softwares.
We will use HTTP Package for API Integration in this blog, so we will need to add the dependency in the pubspec.yaml file.
1 |
http: ^0.12.2 |
For checking out the updated version of package, you can check out the package here – https://pub.dev/packages/http
After adding dependency, we will need to import the package in the file where we want need it.
1 |
import 'package:http/http.dart' as http; |
Here we have used ‘ as ‘http’ ‘ , as we will need to access the methods declared inside this package instead of writing the complete code we will be accessing the methods with ‘http’.
While working on API Integration in Flutter, we will get to hear about the Future, Future Builder ..
So let’s first understand what does these terms mean and what is the use of these terms while integrating APIs.
Future is just like a function which is Asynchronous in nature. Asynchronous means ‘we do not know when it will complete its execution’.
The two keywords ‘async‘ and ‘await‘ are used in asynchronous programming.
Async function works synchronously until the first await keyword is encountered, i.e., within an async function body, all synchronous code before the first await keyword executes immediately.
FutureBuilder helps you in determining the correct state of Future and also helps in displaying the data once the Future has returned.
We will need to create Data Model for the parsing of JSON Data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Trailer { String id; String link; Trailer({this.id, this.link}); Trailer.fromJson(Map<String, dynamic> json) { id = json['id']; link = json['link']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['link'] = this.link; return data; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
class MovieData { String id; String title; String year; String length; String rating; String ratingVotes; String poster; String plot; Trailer trailer; MovieData( {this.id, this.title, this.year, this.length, this.rating, this.ratingVotes, this.poster, this.plot, this.trailer, }); MovieData.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; year = json['year']; length = json['length']; rating = json['rating']; ratingVotes = json['rating_votes']; poster = json['poster']; plot = json['plot']; trailer = json['trailer'] != null ? new Trailer.fromJson(json['trailer']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['title'] = this.title; data['year'] = this.year; data['length'] = this.length; data['rating'] = this.rating; data['rating_votes'] = this.ratingVotes; data['poster'] = this.poster; data['plot'] = this.plot; if (this.trailer != null) { data['trailer'] = this.trailer.toJson(); } return data; } } |
API Integration in Flutter Code
For decoding JSON Data, we will need to import ‘dart:convert’ which provides us the json.decode() method.
Here’s the final code,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:url_launcher/url_launcher.dart'; import 'dart:convert'; import 'package:movie_app/movie.model.dart'; class MovieDetail extends StatefulWidget { @override _MovieDetailState createState() => _MovieDetailState(); } class _MovieDetailState extends State<MovieDetail> { Map<String, String> queryParams = { 'x-rapidapi-key': 'Enter your API Key', 'x-rapidapi-host': 'imdb-internet-movie-database-unofficial.p.rapidapi.com', }; Future<MovieData> getResponse() async { var responseData = await http.get( 'https://imdb-internet-movie-database-unofficial.p.rapidapi.com/film/tt1375666', headers: queryParams); print("Response" + responseData.body); var data = json.decode(responseData.body); var newData = MovieData.fromJson(data); return newData; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Movie Detail"), backgroundColor: Colors.black, ), body: SingleChildScrollView( child: FutureBuilder<MovieData>( future: getResponse(), builder: (context, snapshot) { if (snapshot.hasData) { var data = snapshot.data; return Column( children: [ Stack( children: [ Container( height: MediaQuery.of(context).size.height / 1.5, width: MediaQuery.of(context).size.width, child: Image.network( data.poster, fit: BoxFit.cover, ), ), Container( height: MediaQuery.of(context).size.height / 1.5, color: Colors.black.withOpacity(0.4), ), Column( children: [ Container( height: MediaQuery.of(context).size.height / 1.8, ), Align( alignment: Alignment.bottomCenter, child: ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(40.0), topRight: Radius.circular(40.0)), child: Container( color: Colors.white, height: MediaQuery.of(context).size.height, child: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(data.title, style: TextStyle( fontSize: 24.0, color: Colors.black, fontWeight: FontWeight.bold)), Padding( padding: const EdgeInsets.fromLTRB(0.0,8.0,8.0,8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(data.year), Text("Rating : ${data.rating}"), Row( children: [ Icon(Icons .access_time_outlined), Text(data.length), ], ), ], ), ), Text("PLOT", style: TextStyle( fontSize: 20.0, color: Colors.black, fontWeight: FontWeight.bold)), SizedBox(height: 10.0,), Text(data.plot, style: TextStyle( fontSize: 16.0, color: Colors.black, )), SizedBox(height: 20.0,), SizedBox( width: MediaQuery.of(context).size.width, height: 60.0, child: RaisedButton( color: Colors.black, onPressed: (){ if (data.trailer.link != null){ launch(data.trailer.link); } else{ showDialog(context: context,child: Text("Something went wrong")); } }, child: Text("Checkout the Trailer",style: TextStyle(color: Colors.white),), ), ) ], ), ), ), ), ), ], ), ], ), ], ); } else { return Center(child: CircularProgressIndicator()); } }), |
In this code, we have created a Future method which returns an Instance of MovieData Model.
Within the FutureBuilder widget, we have created our UI and the future property takes the Future method which is getResponse() method.
The output of the code is —
Conclusion
In this blog, we have discussed the API Integration in Flutter with JSON Parsing using HTTP Package.
I hope it will help you in understanding the basic concepts.
You may also check our blog on API Calling through Retrofit – https://mobikul.com/retrofit-api-calling-in-flutter/
Thank you for reading!!