Created
July 22, 2020 17:45
-
-
Save nandanhere/6053be9c8ce91b890350902fdff91262 to your computer and use it in GitHub Desktop.
How to use Future and async property to get a .json file from an api #basics #flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///First Obtain an api link with your key: when the api link is called a json file will be sent to the caller. the json file is in an unprocessed format so you will convert it. | |
///Since you are calling the api through a network, the app is subject to certain errors and linking problems, so we use something called Future, IE the state of the object is set sometime in the future. | |
///To declare a widget that uses a future state, we use something called a futureBuilder.Essentialy a futureBuilder takes the state of something, and if it has a future and if it has obtained it, it will update it. so you dont have to worry about setstate stuff. | |
import 'package:flutter/material.dart'; | |
///Note: you need these imports to make it work | |
import 'package:http/http.dart' as http; | |
import 'dart:convert'; | |
// To learn Json, i declared a class JsonData: it can be named anything relative to the topic. for example for a movie app that uses an api that deals with a json file | |
// which contains all the movie data, you need to create a Movie class which contains all the relevant data related to the movie, such as title, plot, genres, cast, etc | |
///Here is JsonData Class:- | |
class JsonData { | |
final String firstName; | |
final String lastName; | |
final String email; | |
final String gender; | |
JsonData(this.firstName, this.lastName, this.email, this.gender); | |
} | |
///The simple api that i used has the parameters firstname, lastname, email and gender. | |
///if you look at the raw data file of the json sent from the api, it would look like this if it were only one id: | |
///[{ "id":1 , "firstname":"Care", "lastname":"Lambeth" , "gender":"Male" ,"email":"[email protected]" }] // i added more spaces so it becomes readable. | |
/// #1 How do i Acess the json? | |
/// You can acess it by using the http.get(link_of_your_api_with_key) in an async function. | |
/// Eg : var jsonfile = await https://my.api.jsonfiles.com/nanjsonspyro.json?key=4b967da0"); | |
/// #2 What do i do to use this file | |
/// After getting the jsonfile, we convert it to a json format which is readable by dart. we use json.decode(source_of_the_raw_file.body) for this and assigning a variable to this data. | |
/// this allows dart to look at the jsonfile as a list of .json objects. | |
//#3 | |
//How does this relate to the futureBuilder thing? | |
/// When you are creating a state of the app in the start, you will call an asynchronous function, which will take the json raw file, Convert it appropriately to a list and give it to the | |
/// futurebuilder as a future | |
/// What is a snapshot? | |
/// a snapshot is what the List of instances has at a particular point. To deal with scenarios where the jsondatas list is empty or if it is waiting to get the data , we use the switch | |
/// which looks at the connection state of the snapshot and decides to return or perform the specified statements. | |
///#5 How do i acess the data then? | |
///You refer to the snapshot data. in a builder you usually use an index. so the syntax is snapshot.data[index].variable_name | |
// Here is the function you declare in the statefulwidget class .Observe the async property | |
Future<List<JsonData>> _jsondata() async { | |
List<JsonData> jsondatas = | |
[]; // initially we create a list of the class type so that in the future it is filled with class instances | |
var jsonfile = await http | |
.get("https://my.api.jsonfiles.com/nanjsonspyro.json?key=4b967da0"); | |
var info = json.decode(jsonfile.body); | |
// Here info is a List of json objects | |
// We loop through the list and | |
for (var value in info) { | |
JsonData instance = JsonData( | |
value['firstname'], value['lastname'], value['gender'], value['email']); | |
jsondatas.add(instance); | |
} | |
return jsondatas; | |
//if all goes well, you are returning a list of class instances with appropriate data. | |
} | |
///Now, We can use this data by implementing the FutureBuilder Widget which uses our jsondatas list. | |
Widget i = FutureBuilder( | |
future: _jsondata(), | |
builder: (BuildContext context, AsyncSnapshot snapshot) { | |
//#4 | |
switch (snapshot.connectionState) { | |
case ConnectionState.waiting: | |
return new Container( | |
child: Text("loading"), | |
); | |
case ConnectionState.active: | |
return new Container( | |
child: Text("active"), | |
); | |
case ConnectionState.none: | |
return new Container( | |
child: Text("none"), | |
); | |
case ConnectionState.done: | |
if (snapshot.error != null) { | |
return new Center(child: Text("error")); | |
} else | |
return Container( | |
child: new ListView.builder( | |
itemCount: snapshot.data.length, | |
itemBuilder: (BuildContext context, int index) { | |
Column col = Column( | |
children: <Widget>[ | |
ListTile( | |
title: Text("${snapshot.data[index].firstName} " + | |
snapshot.data[index].lastName), | |
subtitle: Text("${snapshot.data[index].email}"), | |
trailing: Container( | |
child: Text("${snapshot.data[index].gender}"), | |
), | |
), | |
], | |
); | |
if (index.isOdd) { | |
col.children.insert(0, Divider()); | |
} | |
return col; | |
}, | |
), | |
); | |
} | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment