API’s in Flutter (A Complete Beginners Guide)
By: Thankgod Chiagozie
Tags: Flutter App Development

Yeah so maybe so you might have done your first flutter create and you’re like oh what next should I try and you hear (do API’s with flutter that’s a great start) and you are wondering what API’s are and what they do well this course is for you. I will show you how to make those API calls and how to present them to the UI. I’ll be using packages http,flutter_spinkit

Firstly, an application program interface (API) is a set of routines, protocols, and tools for building software applications (Very Big English).

Let me Explain:

Take for example I give you an skeleton to make the face of it, and when I told you this I also told you that you can get the items you need to make the face from a particular box (The box is your API). In that box you’ll have pair of eyes,pair of ears, a nose, a mouth and hair (if you deem it ) So basically your box is an API (well technically I don’t want to start writing something elaborate about API’s well at least I’ve left you curious you might just want to learn about API’s). Enough of that back to our box so you can get something from this box,

remove something from the box etc(You could also read on HTTP Headers would give you an understanding).

Okay, now we might have established an understanding or a (confusion) here well hopefully it’s the latter we need to move to the next thing which is actually what we are going to be trying to achieve today, that being making an API in Flutter.

Before, we actually make an app in flutter using an API we need some key things;

We need to make an API call (go to the box). A model class (this is like a register telling you everything in the box). The apps UI (the face we are building we just need to make the face we don’t need legs or hands on the face because they are in the box).

Firstly, I assume you already know how to start a fresh flutter project but if you don’t I don’t think you need to be reading this right now (sorry know your basics), but if you do know how to create a fresh flutter project then let’s continue. I’ll give you a minute to do that …………………..(common am just kidding).

Now, we’ve created our fresh flutter project, remember those key things well creating a fresh project made a UI layer for us, so we’ll just tweak it after we do our model class and our api call. So for this demo i’ll be using http://newsapi.org/v2/everything?q=bitcoin&from=2020-02-08&sortBy=publishedAt&apiKey=(you get this part when you create account and I really can’t afford sharing mine to create an account go to https://newsapi.org)and you are good to go well let me give you a sec to get your account all set up.

So now we’re done setting up our account, remember that link that I said I can’t share a part of it with you(apiKey part) yeah that part. I want you to copy the link and put it on your browser just to see what it looks like.

Now you have seen it I know you are wondering (what is going on here) well don’t be weary, I want you to copy all that is on your screen. Now we want to generate our model class so now there are 2 tools for that ;

I want you to go to one of these 2 url’s and in the area designated to put your json paste what you already copied there and click generate dart for (1),(2) does it by itself (Just remember to put names you want your model class would answer). So now copy the code you see on the screen and create file in the lib folder and name the file model.dart then you paste all the code it should like this mind you I named mine ‘Rates’ yes cos I can :)

class Rates { final String status; final int totalResults; final List<Article> articles; Rates({ this.status, this.totalResults, this.articles, }); factory Rates.fromJson(Map<String, dynamic> json) => Rates( status: json["status"], totalResults: json["totalResults"], articles: List<Article>.from(json["articles"].map((x) => Article.fromJson(x))), ); Map<String, dynamic> toJson() => { "status": status, "totalResults": totalResults, "articles": List<dynamic>.from(articles.map((x) => x.toJson())), }; } class Article { final Source source; final String author; final String title; final String description; final String url; final String urlToImage; final DateTime publishedAt; final String content; Article({ this.source, this.author, this.title, this.description, this.url, this.urlToImage, this.publishedAt, this.content, }); factory Article.fromJson(Map<String, dynamic> json) => Article( source: Source.fromJson(json["source"]), author: json["author"] == null ? null : json["author"], title: json["title"], description: json["description"], url: json["url"], urlToImage: json["urlToImage"], publishedAt: DateTime.parse(json["publishedAt"]), content: json["content"] == null ? null : json["content"], ); Map<String, dynamic> toJson() => { "source": source.toJson(), "author": author == null ? null : author, "title": title, "description": description, "url": url, "urlToImage": urlToImage, "publishedAt": publishedAt.toIso8601String(), "content": content == null ? null : content, }; } class Source { final Id id; final Name name; Source({ this.id, this.name, }); factory Source.fromJson(Map<String, dynamic> json) => Source( id: idValues.map[json["id"]], name: nameValues.map[json["name"]], ); Map<String, dynamic> toJson() => { "id": idValues.reverse[id], "name": nameValues.reverse[name], }; } enum Id { TECHCRUNCH } final idValues = EnumValues({ "techcrunch": Id.TECHCRUNCH }); enum Name { TECH_CRUNCH } final nameValues = EnumValues({ "TechCrunch": Name.TECH_CRUNCH }); class EnumValues<T> { Map<String, T> map; Map<T, String> reverseMap; EnumValues(this.map); Map<T, String> get reverse { if (reverseMap == null) { reverseMap = map.map((k, v) => new MapEntry(v, k)); } return reverseMap; } }

import 'dart:convert'; import 'package:road_to_flutter_demo/learn/learn_model.dart'; import 'package:http/http.dart' as http; class RatesProvider{ String url = 'http://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=0033eec1ce834b8f93dbd041496980c9'; Future<Rates> getRates() async{ final call = await http.get(url); if(call.statusCode == 200){ return Rates.fromJson(jsonDecode(call.body)); } return null; } }

Now we make an API call like shown above so now we are done with those we now want to go to the UI layer of the app don’t you think??

The UI

import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:road_to_flutter_demo/learn/learn_call.dart'; import 'package:road_to_flutter_demo/learn/learn_model.dart'; import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData.dark(), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { // Future<List<Rates>> rates; // @override // void initState() { // super.initState(); // } RatesProvider ratesProvider = RatesProvider(); @override Widget build(BuildContext context) { return Scaffold( // backgroundColor: Colors.black, appBar: AppBar( // actions: <Widget>[IconButton(icon: Icon(Icons.refresh), onPressed: _newFresh(),)], backgroundColor: Colors.black, title: Text('TechCrunch'), centerTitle: true, ), body: FutureBuilder<Rates>( future: ratesProvider.getRates(), builder: (context,snapshot){ if(snapshot.hasData){ return ListView.builder( itemCount: snapshot.data.articles.length, itemBuilder: (context,index){ return ListTile( // leading: CircleAvatar(child:Image.network('${snapshot.data.articles[index].urlToImage}'),), title: Text(snapshot.data.articles[index].title,style: TextStyle(fontSize: 19, fontWeight: FontWeight.w300),), subtitle: Text((snapshot.data.articles[index].author) == null ? 'Not available' : (snapshot.data.articles[index].author)), trailing: IconButton(icon: Icon(Icons.launch,color: Colors.green,), onPressed: ()async{ Navigator.push(context, MaterialPageRoute( builder: (context) => WebviewScaffold( url: '${snapshot.data.articles[index].url}', appBar: AppBar( centerTitle: true, title: Text('${snapshot.data.articles[index].title}',), elevation: 0, backgroundColor: Colors.black, ), withZoom: true, withLocalStorage: true, hidden: true, initialChild: SpinKitFoldingCube(color: Colors.blue,size: 50,), ) ) ); }, ), ); } ); } return SpinKitPouringHourglass(color: Colors.black,size: 90,); }, ), ); } }

The UI is a bit shitty but well it’s useful for this course, I use a FutureBuilder here and I give it a type of <Rates> as we see in the code above.

Then before that I made an object ‘ratesProvider’ which we see and I also used the object with the getNews() method then in builder parameter we see that it takes a (context, snapshot) this snapshot is what we’ll be using to grab the important stuff as we see down the code we something like “snapshot.hasData” this is confirming if our API call did bring anything, then a ListView.builder widget this widget builds list there is an article available you could use to read on them here in Medium you could read up on them. Now we see something like “snapshot.data.articles[index].title” index is like iterator it goes through a list an returns them accordingly this is what ListView.builder can do for you. With this I think we’ve built our first app with an API yaaaas.

The app UI

This was it’s first form

This UI was later re-updated by me, well if you clone the repo and run on your local device you’d see what i’m talking about clearly for now it would be a goodbye from me.

You could ask me questions on twitter:

Create an Issue on github:

Thank You very much really hope this helps if you have questions pertaining to this article please hit my twitter up i’ll totally respond to you.