If you want your apps to read data from public APIs (here’s a list with thousands of APIs) or communicate with your own custom backend, you’ll need to write some networking code.

Networking Basics

Simple apps that need to talk to a REST API can use the Dart http package. This offers a Future-based API for making network requests, and it works on all platforms since it’s a pure Dart package.

Most REST APIs will respond with data in JSON format, which can be decoded into maps of key-value pairs that are not type-safe.

When reading JSON data, it’s best practice to deserialize and convert it into type-safe model classes. Likewise, you can serialize your models back to JSON data that can be sent over the network. This article covers all the details:

Code Generation

Doing all this by hand is ok if you have very few simple model classes. But if you have many endpoints returning complex data, code generation may be a better option, and the json_annotation package helps with that.

Along with that, you can consider using the freezed package.

For a good intro to code generation and the freezed package, follow this tutorial:

Other Networking Packages

The http package is easy to use and works well for simple apps.

But for apps with more complex requirements, the dio package may be more appropriate.

Dio supports more advanced features such as sending form datarequest cancellationfile downloading, etc.

So, if you need any of the above, dio is a better choice than http.

But even then, you still need to deal with JSON serialization. Wouldn’t it be nice if there was a package that could auto-generate all the networking and serialization code for you?

Luckily, retrofit was created for this purpose. It can auto-generate REST clients for all your models with minimal boilerplate code, so make sure to check it out.

And if you want to go even further and generate REST API clients in Dart from an API schema using OpenAPI, here’s a great session from DartUp 2021:

Daily Challenge - Weather App

The flutter_bloc documentation includes an advanced tutorial showing how to build a Weather app in Flutter:

This includes some advanced features such as dynamic themes, pull-to-refresh and more.

Try building the same application yourself. You can borrow all the networking code from the tutorial, but feel free to implement a different UI or choose a different state management technique if you wish.

Happy Coding!

Questions? Let's chat