Back to code Dart

Una llamada de red con tiempo límite y reintentos

Una función genérica que envuelve cualquier Future: corta si tarda demasiado y reintenta un número fijo de veces.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

En una app móvil la red se cae y vuelve. Una llamada sin tiempo límite deja la pantalla girando para siempre; una sin reintento convierte un túnel en un error.

Dart
import 'dart:async';

Future<T> conReintento<T>(Future<T> Function() tarea, {int intentos = 3, Duration limite = const Duration(seconds: 5)}) async {
  for (var i = 1; ; i++) {
    try {
      return await tarea().timeout(limite);
    } on TimeoutException {
      if (i >= intentos) rethrow;
      print('Intento $i: sin respuesta en ${limite.inSeconds}s, reintento');
    } catch (e) {
      if (i >= intentos) rethrow;
      print('Intento $i falló: $e');
    }
    await Future.delayed(Duration(milliseconds: 300 * i));
  }
}

Future<void> main() async {
  var llamadas = 0;
  final dato = await conReintento(() async {
    llamadas++;
    if (llamadas < 3) throw Exception('red caída');
    return 'perfil cargado';
  });
  print('$dato tras $llamadas intentos');
}

Why it is written this way

  1. timeout convierte una espera eterna en una TimeoutException a los cinco segundos.
  2. rethrow relanza el error original conservando su traza: quien llama ve la causa real.
  3. La pausa crece con cada intento (300, 600, 900 ms) para no insistir sobre una red que recién vuelve.
  4. Al ser genérica, sirve igual para un perfil, una lista o un archivo.
How to try it

Guardalo como reintento.dart y corré: dart run reintento.dart. También corre en dartpad.dev.

Watch out

timeout deja de esperar, pero no cancela la llamada: el pedido sigue vivo por debajo. Para cancelar de verdad hace falta que el cliente HTTP lo soporte.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Tengo esta función de reintento con tiempo límite en Dart. Adaptala para usarla en Flutter con [PAQUETE HTTP: http, dio], que solo reintente errores de red y códigos 5xx (nunca 4xx), que cancele de verdad el pedido al vencer el tiempo y que exponga el estado para mostrar "reintentando…" en pantalla con [GESTOR DE ESTADO]. Mostrame el uso en un botón de recargar.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.
You are writing outside working hours. I will read you as soon as the day starts.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.