Flutter : Fetching & Parsing JSON data

Diego Velasquez
4 min readJul 5, 2018

--

One of the basic things we always do in a mobile application is to fetch data from a REST service.

As a native Android and iOS developer, we can do it using the API that provides the SDK of each platform as well and in most cases we use an external library.

In the case of Android, the best known is RetroFit and in the case of iOS, most opt ​​for AlamoFire.
These libraries make it easier for us to fetch and send data via REST using a simple and easy-to-use API.

In Flutter we can also do it in a simple way, without the need for an external library.

The example that I am going to show you next is a simple screen with a button at the bottom, by pressing the button we will get the data from a REST service and we parsed the JSON to a custom object, we will show a widget while the operation is in progress and finally we show the result

Let’s Code

We create our StateFulWidget which we will call MainFetchData

class MainFetchData extends StatefulWidget {
@override
_MainFetchDataState createState() => _MainFetchDataState();
}
class _MainFetchDataState extends State<MainFetchData> {

@override
Widget build(BuildContext context) {
return Container();
}
}

Now we have to give shape to our screen, we are going to put the content inside a Scaffold, a title in the app bar and a button at the bottom of the screen

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Fetch Data JSON"),
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: new Text("Fetch Data"),
onPressed: () => null,
),
),
body: Container(),
);

We declare two variables inside our Stateful class, one to save the elements that we obtain from the REST service and another to manage the status of the progress bar.

List list = List();
var isLoading = false;

Don’t forget to import the http package that Dart provides us

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

Next, create the method to fetch the REST service

_fetchData() async {
setState(() {
isLoading = true;
});
final response =
await http.get("https://jsonplaceholder.typicode.com/photos");
if (response.statusCode == 200) {
list = json.decode(response.body) as List
setState(() {
isLoading = false;
});
} else {
throw Exception('Failed to load photos');
}
}

After obtaining the result, we have to update the status of the widget, so our code would be as follows

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Fetch Data JSON"),
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: new Text("Fetch Data"),
onPressed: _fetchData,
),
),
body: isLoading
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
contentPadding: EdgeInsets.all(10.0),
title: new Text(list[index]['title']),
trailing: new Image.network(
list[index]['thumbnailUrl'],
fit: BoxFit.cover,
height: 40.0,
width: 40.0,
),
);
}));

Super simple , isn’t it? :)

Improving the code

Now to make it more elegant, instead of getting the attributes directly in the list, we will parse the object we get from the service to a custom class that we created.

Creating our data class name Photo.dart by doing our private constructor, in Dart there is no reserved word for private access, simply use the underscore at the start of the method name or variable.

class Photo {final String title;
final String thumbnailUrl;
Photo._({this.title, this.thumbnailUrl});}

Now create a Factory method to parse the data we obtain from the REST service

class Photo {
final String title;
final String thumbnailUrl;
Photo._({this.title, this.thumbnailUrl});factory Photo.fromJson(Map<String, dynamic> json) {
return new Photo._(
title: json['title'],
thumbnailUrl: json['thumbnailUrl'],
);
}
}

Finally we update our StatefulWidget and this is the final code

Conclusion

As we can see, fetching data in Flutter is very simple, in a few lines of code we were able to create a small example that fetch and shows data.

You can check the source code in my flutter-samples repo https://github.com/diegoveloper/flutter-samples

References

https://flutter.io/cookbook/networking/fetch-data/

--

--