Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to close HTTP Client in Flutter app?

Tags:

flutter

dart

My Flutter mobile app communicates with my back-end server. The docs say it's better to use Client class (IOClient) than plain get, put, etc. methods to maintain persistent connections across multiple requests to the same server. Docs also say that:

It's important to close each client when it's done being used; failing to do so can cause the Dart process to hang.

I don't understand when I need to close the client, because almost all app screens require HTTP connection to the same server. What's the best practice here?

Update:

Is it OK to close Client only before app is terminated, or should I close it every time app is hidden (goes to paused state)?

like image 737
flomaster Avatar asked Sep 05 '25 07:09

flomaster


1 Answers

I personnaly think that closing client after each user action is the best practise.

What i call an "user action" can be constituted of multiple API request.

So i think the best is something like that:

var client = http.Client();
try {
  var response = await client.post(
      Uri.https('my-api-site.com', 'users/add'),
      body: {'firstname': 'Alain', 'Lastname': 'Deseine'});
  var Response = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
  ...
  // Add here every API request that you need to complete the users action
} finally {
  // Then finally destroy the client.
  client.close();
}
like image 152
Alaindeseine Avatar answered Sep 07 '25 21:09

Alaindeseine