Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 73 ยท Networking and data

HTTP Requests and JSON

Learn how a Flutter app talks to a server: the http and dio packages, GET and POST, decoding JSON into model classes, json_serializable and error handling.

Almost every real app talks to a server: it loads a list of products, posts a login form, or saves a note. In Flutter this is plain Dart code. You send an HTTP request, wait for the response, turn the JSON text into typed Dart objects, and hand those objects to your widgets.

This lesson covers the two popular packages (http and dio), how to write model classes, how to generate the parsing code, and how to handle the many ways a request can fail. It builds on Futures, async/await and Streams and Collections and Generics.

Real vs stand-in. The Dart code is real Flutter code and is read-only here, because the site cannot run Dart or open real network connections from your lessons. The live examples are JavaScript stand-ins: a fake server built with Response objects, and the same request, decode, model and error steps you would write in Dart.

From server to screen

Request Send GET or POST to a URL.
Response Status code plus a body string.
Decode Turn JSON text into maps.
Model Typed Dart objects for widgets.
1 / 2

Adding the http package

Dart's core libraries have a low-level client, but most apps use the small http package. Add it to pubspec.yaml with flutter pub add http, then import it:

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

Future<void> main() async {
  final uri = Uri.parse('https://api.example.com/products?limit=5');
  final response = await http.get(uri);

  print(response.statusCode); // 200
  print(response.body);       // a String with JSON text
}

Always build URLs with Uri rather than string concatenation. Uri.https('api.example.com', '/products', {'limit': '5'}) escapes query values for you.

An important detail: http.get only throws when no response arrives at all (no connection, DNS failure, timeout). A 404 or 500 comes back as a normal Response with that status code. You must check statusCode yourself.

Android and iOS permissions

On Android you must declare the internet permission in android/app/src/main/AndroidManifest.xml for release builds: <uses-permission android:name="android.permission.INTERNET" />. Debug builds add it for you, which is why a "works in debug, fails in release" bug is almost always this line. Plain http:// (not https://) URLs are blocked by default on both Android and iOS, so use HTTPS for real servers.

POST, headers and bodies

To send data, encode it to a JSON string and set the content type:

DART
Future<http.Response> createNote(String text) {
  return http.post(
    Uri.parse('https://api.example.com/notes'),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $token',
    },
    body: jsonEncode({'text': text}),
  );
}

jsonEncode turns maps, lists, strings, numbers, booleans and null into JSON text. Passing a Map directly as body would send it form-encoded instead, which is a common surprise.

Decoding JSON into models

jsonDecode returns dynamic: a Map<String, dynamic> for an object, a List<dynamic> for an array. Working with raw maps spreads string keys and casts all over your UI. Write a model class instead and do the conversion in one place:

DART
class Product {
  const Product({required this.id, required this.name, required this.price, this.imageUrl});

  final int id;
  final String name;
  final double price;
  final String? imageUrl;

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json['id'] as int,
      name: json['name'] as String,
      price: (json['price'] as num).toDouble(),
      imageUrl: json['image_url'] as String?,
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'name': name,
        'price': price,
        'image_url': imageUrl,
      };
}

Two details matter here. A JSON number such as 10 decodes as int while 10.5 decodes as double, so read numbers as num and convert. And a nullable field uses as String?, which accepts a missing key (see Null Safety).

A repository function then hides the HTTP details from the UI:

DART
Future<List<Product>> fetchProducts() async {
  final response = await http
      .get(Uri.parse('https://api.example.com/products'))
      .timeout(const Duration(seconds: 10));

  if (response.statusCode != 200) {
    throw ApiException(response.statusCode);
  }
  final list = jsonDecode(response.body) as List<dynamic>;
  return list
      .map((item) => Product.fromJson(item as Map<String, dynamic>))
      .toList();
}

Stand-in: a fake server and the full pipeline

The first example builds a fake fetch that answers like a server, then runs the exact steps: request, status check, decode, model.

JS Request, decode and model

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the decoded data never reaches the "UI" as a raw map. The label getter works on a typed object, which is exactly what you want in a widget's build method.

json_serializable

Writing fromJson and toJson by hand is fine for small models and tedious for fifty. The json_serializable package generates them. You add an annotation and a part line, then run the build tool:

DART
import 'package:json_annotation/json_annotation.dart';

part 'product.g.dart';

@JsonSerializable()
class Product {
  const Product({required this.id, required this.name, required this.price, this.imageUrl});

  final int id;
  final String name;
  final double price;

  @JsonKey(name: 'image_url')
  final String? imageUrl;

  factory Product.fromJson(Map<String, dynamic> json) => _$ProductFromJson(json);
  Map<String, dynamic> toJson() => _$ProductToJson(this);
}
TEXT
dart run build_runner build --delete-conflicting-outputs

The tool writes product.g.dart with the real conversion code. It is plain Dart with no reflection, so it is fast and works with tree shaking. Newer alternatives such as freezed add immutability, copyWith and unions on top, but the idea is the same.

The dio package

dio is a heavier client with features you otherwise write yourself: base URLs, interceptors (add an auth header to every call, log requests, refresh a token on a 401), cancellation, timeouts, uploads with progress and automatic JSON decoding.

DART
final dio = Dio(BaseOptions(
  baseUrl: 'https://api.example.com',
  connectTimeout: const Duration(seconds: 5),
  receiveTimeout: const Duration(seconds: 10),
));

dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    options.headers['Authorization'] = 'Bearer $token';
    handler.next(options);
  },
));

final response = await dio.get('/products', queryParameters: {'limit': 5});
final list = response.data as List<dynamic>; // already decoded

Unlike http, dio throws a DioException for non-2xx statuses by default. Choose http for a few simple calls, and dio when interceptors and cancellation pay off.

Error handling

A robust request function separates the failure kinds so the UI can say something useful:

DART
sealed class LoadResult {}
class Loaded extends LoadResult { Loaded(this.products); final List<Product> products; }
class Failed extends LoadResult { Failed(this.message); final String message; }

Future<LoadResult> loadProducts() async {
  try {
    return Loaded(await fetchProducts());
  } on SocketException {
    return Failed('No internet connection.');
  } on TimeoutException {
    return Failed('The server took too long.');
  } on FormatException {
    return Failed('The server sent something unexpected.');
  } on ApiException catch (e) {
    return Failed('Server error ${e.statusCode}.');
  }
}

jsonDecode throws FormatException for invalid JSON, and a wrong as cast throws TypeError, so a missing field surfaces as a failure rather than silently showing null. Never decode on the main isolate for huge payloads: compute(parseProducts, body) or Isolate.run keeps a multi-megabyte parse from dropping frames.

JS Handling every kind of failure

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each outcome becomes a small value the UI can switch on. How a widget turns those values into a spinner, an error message and a list is the topic of FutureBuilder, StreamBuilder and Async UI.

Practical advice

  • Keep HTTP out of widgets. Put requests in a repository class so you can swap it for a fake in tests (Choosing State Management and App Architecture).
  • Keep secrets out of the app. Anything in your binary can be extracted; see Security in Flutter Apps.
  • Set timeouts. The default can wait a very long time on a bad connection.
  • Web builds follow browser rules. Flutter web needs CORS headers from your server; the same code that works on a phone may be blocked in a browser.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You call http.get and the server answers 404. What happens?

    The http package only throws when no response arrives. Bad status codes are normal responses.
  2. 2. What does jsonDecode return for a JSON object?

    jsonDecode returns dynamic: a Map for objects and a List for arrays. A model's fromJson turns the map into a typed object.
  3. 3. Why read a JSON price as num and call toDouble()?

    A whole-number JSON value arrives as int. Casting it to double throws a TypeError, while num accepts both.
  4. 4. What does json_serializable do?

    It generates the conversion code into a .g.dart file at build time, with no runtime reflection.
  5. 5. Which problem is typical for a release build that works in debug on Android?

    Debug builds add the permission automatically; release builds need it declared.

Summary

  • Use the http package for simple calls and dio when you need interceptors, cancellation or progress.
  • http throws only when nothing arrives; always check statusCode.
  • Decode with jsonDecode, convert in a model's fromJson, and read numbers as num.
  • Generate boilerplate with json_serializable and build_runner.
  • Turn timeouts, bad status codes and bad JSON into explicit results the UI can show.

Next: FutureBuilder, StreamBuilder and Async UI