{
    "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency",
    "locale": "nl",
    "title": "Concurrency in Dart | DeLaParra Services",
    "description": "Met concurrency kan een Dart-programma voortgang maken met meerdere taken, via asynchrone operaties of isolates.",
    "alternates": {
        "en": "https://delaparra-services.nl/skills/flutter-concurrency",
        "nl": "https://delaparra-services.nl/nl/skills/flutter-concurrency"
    },
    "formats": {
        "csv": "https://delaparra-services.nl/nl/skills/flutter-concurrency.csv",
        "md": "https://delaparra-services.nl/nl/skills/flutter-concurrency.md",
        "json": "https://delaparra-services.nl/nl/skills/flutter-concurrency.json",
        "zip": "https://delaparra-services.nl/nl/skills/flutter-concurrency.zip",
        "pdf": "https://delaparra-services.nl/nl/skills/flutter-concurrency.pdf"
    },
    "downloads": [
        {
            "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency.csv",
            "encodingFormat": "text/csv",
            "name": "flutter-concurrency.csv"
        },
        {
            "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency.json",
            "encodingFormat": "application/json",
            "name": "flutter-concurrency.json"
        },
        {
            "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency.md",
            "encodingFormat": "text/markdown",
            "name": "flutter-concurrency.md"
        },
        {
            "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency.pdf",
            "encodingFormat": "application/pdf",
            "name": "flutter-concurrency.pdf"
        },
        {
            "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency.zip",
            "encodingFormat": "application/zip",
            "name": "flutter-concurrency.zip"
        },
        {
            "url": "https://delaparra-services.nl/skills/flutter-concurrency/download",
            "encodingFormat": "application/zip",
            "name": "flutter-concurrency-files.zip"
        }
    ],
    "markdown": "# Concurrency in Dart\n\n \n\nMet concurrency kan een Dart-programma voortgang maken met meerdere taken, via asynchrone operaties of isolates.\n\n \n\n**Licentie** MIT\n\n \n\n**Bron** gabuldev/flutter-skills\n\n [Download zip](<https://delaparra-services.nl/skills/flutter-concurrency/download>)   \n\nYou are implementing concurrency for a Flutter feature. Choose the pattern based on the skill argument, if one was given, or on the context of the operation.\n\n \n\n## Decision Framework\n\n \n\nPick the right tool for the workload:\n\n    Workload Pattern Examples     I/O (network, storage) ` async/await ` Dio API calls, SharedPreferences, Hive reads   CPU \\< 16 ms ` async/await ` Small list transforms, formatting   One-time heavy CPU ` Isolate.run() ` PDF receipt generation, large JSON parsing   Continuous background ` Isolate.spawn() ` with ports Payment status polling, data sync    \n\n**Rule of thumb**: if it does NOT block the main isolate for more than one frame (~16 ms), use ` async/await `. Otherwise, offload to an isolate.\n\n  \n\n## Pattern 1: Async in Cubits (default)\n\n \n\nBest for: API calls, storage reads, form submissions.\n\n \n\nControllers follow the Loading → Success/Failure emission pattern:\n\n \n\n```\nclass OrderController extends Cubit<OrderStatus> {\n  final OrderRepository _repository;\n\n  OrderController(this._repository) : super(const OrderInitial());\n\n  Future<void> loadOrders() async {\n    emit(const OrderLoading());\n    try {\n      final orders = await _repository.getOrders();\n      emit(OrderSuccess(orders));\n    } on DioException catch (e) {\n      emit(OrderFailure(e.message ?? 'Erro ao carregar pedidos'));\n    } catch (e) {\n      emit(OrderFailure(e.toString()));\n    }\n  }\n}\n```\n\n \n\n**Rules:**\n\n \n\n- Always emit ` Loading ` before the async call \n- Catch ` DioException ` separately for HTTP errors \n- Never emit after the Cubit is closed (see Pitfalls section)\n\n  \n\n## Pattern 2: Stream Management with RxDart\n\n \n\nBest for: real-time data, debounced search, reactive pipelines.\n\n \n\n```\nclass SearchController extends Cubit<SearchStatus> {\n  final SearchRepository _repository;\n  final _querySubject = BehaviorSubject<String>.seeded('');\n  StreamSubscription<String>? _querySub;\n\n  SearchController(this._repository) : super(const SearchInitial()) {\n    _querySub = _querySubject\n        .debounceTime(const Duration(milliseconds: 400))\n        .where((q) => q.length >= 2)\n        .distinct()\n        .listen(_performSearch);\n  }\n\n  void onQueryChanged(String query) => _querySubject.add(query);\n\n  Future<void> _performSearch(String query) async {\n    emit(const SearchLoading());\n    try {\n      final results = await _repository.search(query);\n      emit(SearchSuccess(results));\n    } catch (e) {\n      emit(SearchFailure(e.toString()));\n    }\n  }\n\n  @override\n  Future<void> close() {\n    _querySub?.cancel();\n    _querySubject.close();\n    return super.close();\n  }\n}\n```\n\n \n\n**Rules:**\n\n \n\n- Always dispose ` BehaviorSubject ` and cancel ` StreamSubscription ` in ` close() ` \n- Use ` debounceTime ` for user input to avoid excessive API calls \n- Use ` distinct() ` to skip duplicate emissions \n- Use ` BehaviorSubject ` (not ` PublishSubject `) when you need the latest value on subscription\n\n  \n\n## Pattern 3: Isolate.run() for One-Time Heavy Work\n\n \n\nBest for: PDF receipt generation, parsing large JSON payloads, image processing.\n\n \n\n### PDF Receipt Generation\n\n \n\n```\nclass ReceiptController extends Cubit<ReceiptStatus> {\n  ReceiptController() : super(const ReceiptInitial());\n\n  Future<void> generateReceipt(Order order) async {\n    emit(const ReceiptLoading());\n    try {\n      // Offload PDF generation to a background isolate\n      final pdfBytes = await Isolate.run(() => _buildReceiptPdf(order));\n      emit(ReceiptSuccess(pdfBytes));\n    } catch (e) {\n      emit(ReceiptFailure('Erro ao gerar comprovante: $e'));\n    }\n  }\n}\n\n// Top-level or static function (required for Isolate.run)\nUint8List _buildReceiptPdf(Order order) {\n  final pdf = pw.Document();\n  pdf.addPage(\n    pw.Page(\n      pageFormat: PdfPageFormat(80 * PdfPageFormat.mm, double.infinity),\n      build: (context) => pw.Column(\n        crossAxisAlignment: pw.CrossAxisAlignment.start,\n        children: [\n          pw.Text('Pedido #${order.id}', style: pw.TextStyle(fontSize: 14, fontWeight: pw.FontWeight.bold)),\n          pw.SizedBox(height: 4),\n          ...order.items.map((item) => pw.Text('${item.quantity}x ${item.name} - R\\$ ${item.total.toStringAsFixed(2)}')),\n          pw.Divider(),\n          pw.Text('Total: R\\$ ${order.total.toStringAsFixed(2)}', style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),\n        ],\n      ),\n    ),\n  );\n  return pdf.save();\n}\n```\n\n \n\n**Rules:**\n\n \n\n- The function passed to ` Isolate.run() ` must be **top-level** or **static** (no closures over instance state) \n- All arguments must be **sendable** across isolate boundaries (primitives, Lists, Maps, typed data classes — no Cubits, no Dio instances) \n- ` Isolate.run() ` handles spawning and killing the isolate automatically\n\n \n\n### Large Data Processing\n\n \n\n```\nFuture<void> processReport(List<Map<String, dynamic>> rawData) async {\n  emit(const ReportLoading());\n  try {\n    final processed = await Isolate.run(() => _aggregateReportData(rawData));\n    emit(ReportSuccess(processed));\n  } catch (e) {\n    emit(ReportFailure('Erro ao processar relatório: $e'));\n  }\n}\n\n// Top-level function\nReportData _aggregateReportData(List<Map<String, dynamic>> rawData) {\n  // Heavy aggregation, grouping, sorting — runs off the main isolate\n  final grouped = <String, double>{};\n  for (final entry in rawData) {\n    final category = entry['category'] as String;\n    final value = (entry['value'] as num).toDouble();\n    grouped[category] = (grouped[category] ?? 0) + value;\n  }\n  return ReportData(grouped);\n}\n```\n\n  \n\n## Pattern 4: Isolate.spawn() for Continuous Background Work\n\n \n\nBest for: payment status polling, background data sync.\n\n \n\n```\nclass PaymentPollingService {\n  Isolate? _isolate;\n  ReceivePort? _receivePort;\n  StreamSubscription? _portSub;\n\n  Future<void> startPolling(String transactionId) async {\n    _receivePort = ReceivePort();\n\n    _isolate = await Isolate.spawn(\n      _pollPaymentStatus,\n      _PollingArgs(transactionId, _receivePort!.sendPort),\n    );\n\n    _portSub = _receivePort!.listen((message) {\n      if (message is PaymentStatusUpdate) {\n        // Forward to EventBus/Broker or Cubit\n        Broker.instance.fire(PaymentStatusEvent(message));\n      }\n    });\n  }\n\n  void stopPolling() {\n    _portSub?.cancel();\n    _receivePort?.close();\n    _isolate?.kill(priority: Isolate.immediate);\n    _isolate = null;\n  }\n}\n\n// Top-level function\nvoid _pollPaymentStatus(_PollingArgs args) async {\n  while (true) {\n    await Future.delayed(const Duration(seconds: 3));\n    // Simulate checking payment status (no Dio here — use dart:io HttpClient or pass data via ports)\n    final status = await _checkStatus(args.transactionId);\n    args.sendPort.send(PaymentStatusUpdate(status));\n    if (status == 'approved' || status == 'declined') break;\n  }\n}\n\nclass _PollingArgs {\n  final String transactionId;\n  final SendPort sendPort;\n  _PollingArgs(this.transactionId, this.sendPort);\n}\n```\n\n \n\n**Rules:**\n\n \n\n- Always provide a way to **stop** the isolate (` kill() ` + close the port) \n- The spawned function cannot use objects from the main isolate (no Dio, no Cubit, no repos) \n- Communicate via ` SendPort ` / ` ReceivePort ` only with sendable types \n- Clean up in the service's ` dispose() ` or controller's ` close() `\n\n  \n\n## FutureBuilder vs BlocBuilder\n\n \n\nWith the **Cubit pattern**, prefer ` BlocBuilder ` over ` FutureBuilder `.\n\n     ` FutureBuilder ` ` BlocBuilder `     Use when Quick prototype, one-off Future with no state The default for anything with state   Re-triggers on rebuild Yes (unless Future is cached) No (reacts to state only)   Testable Hard Easy (mock Cubit, emit states)   Error handling In builder ` snapshot.hasError ` In state class (` FailureStatus `)    \n\n```\n// PREFERRED\nBlocBuilder<OrderController, OrderStatus>(\n  builder: (context, state) {\n    if (state is OrderLoading) return const CircularProgressIndicator();\n    if (state is OrderSuccess) return OrderListView(orders: state.orders);\n    if (state is OrderFailure) return ErrorWidget(message: state.message);\n    return const SizedBox.shrink();\n  },\n)\n\n// AVOID unless truly one-off and outside of a Cubit-managed feature\nFutureBuilder<List<Order>>(\n  future: _future, // must be cached in initState, never inline\n  builder: (context, snapshot) { ... },\n)\n```\n\n  \n\n## Cancellation\n\n \n\n### HTTP Requests with Dio CancelToken\n\n \n\n```\nclass ProductController extends Cubit<ProductStatus> {\n  final ProductRepository _repository;\n  CancelToken? _cancelToken;\n\n  ProductController(this._repository) : super(const ProductInitial());\n\n  Future<void> loadProducts() async {\n    _cancelToken?.cancel('New request started');\n    _cancelToken = CancelToken();\n\n    emit(const ProductLoading());\n    try {\n      final products = await _repository.getProducts(cancelToken: _cancelToken!);\n      emit(ProductSuccess(products));\n    } on DioException catch (e) {\n      if (e.type == DioExceptionType.cancel) return; // silently ignore\n      emit(ProductFailure(e.message ?? 'Erro'));\n    }\n  }\n\n  @override\n  Future<void> close() {\n    _cancelToken?.cancel('Controller closed');\n    return super.close();\n  }\n}\n```\n\n \n\n### Stream Subscriptions\n\n \n\n```\n@override\nFuture<void> close() {\n  _subscription?.cancel();  // StreamSubscription\n  _subject.close();         // BehaviorSubject\n  _cancelToken?.cancel();   // Dio CancelToken\n  return super.close();\n}\n```\n\n \n\n**Rule:** Every subscription, subject, and cancel token created in a controller **must** be cleaned up in ` close() `.\n\n  \n\n## Common Pitfalls\n\n \n\n### 1. Emit after close\n\n \n\n```\n// BAD — can throw StateError if Cubit was closed during the await\nFuture<void> load() async {\n  emit(const Loading());\n  final data = await _repo.fetch();\n  emit(Success(data)); // 💥 if navigated away\n}\n\n// GOOD — guard before emitting\nFuture<void> load() async {\n  emit(const Loading());\n  final data = await _repo.fetch();\n  if (isClosed) return;\n  emit(Success(data));\n}\n```\n\n \n\n### 2. Uncancelled subscriptions\n\n \n\n```\n// BAD — leaks the subscription\nclass MyController extends Cubit<MyStatus> {\n  MyController(Stream<int> stream) : super(const MyInitial()) {\n    stream.listen((val) => emit(MyUpdated(val))); // never cancelled\n  }\n}\n\n// GOOD\nclass MyController extends Cubit<MyStatus> {\n  late final StreamSubscription<int> _sub;\n  MyController(Stream<int> stream) : super(const MyInitial()) {\n    _sub = stream.listen((val) => emit(MyUpdated(val)));\n  }\n  @override\n  Future<void> close() { _sub.cancel(); return super.close(); }\n}\n```\n\n \n\n### 3. Blocking the main isolate\n\n \n\n```\n// BAD — 200ms of JSON parsing freezes the UI\nfinal data = jsonDecode(hugeJsonString) as List;\n\n// GOOD — offload to isolate\nfinal data = await Isolate.run(() => jsonDecode(hugeJsonString) as List);\n```\n\n \n\n### 4. Passing non-sendable objects to isolates\n\n \n\n```\n// BAD — Dio is not sendable\nawait Isolate.run(() => dio.get('/endpoint')); // 💥 runtime error\n\n// GOOD — fetch on main, process on isolate\nfinal response = await dio.get('/endpoint');\nfinal processed = await Isolate.run(() => _heavyParse(response.data));\n```\n\n \n\n### 5. FutureBuilder with inline Future\n\n \n\n```\n// BAD — re-creates the Future on every build\nWidget build(BuildContext context) {\n  return FutureBuilder(\n    future: repository.load(), // called every rebuild!\n    builder: (ctx, snap) => ...,\n  );\n}\n\n// GOOD — cache the Future\nlate final _future = repository.load();\nWidget build(BuildContext context) {\n  return FutureBuilder(future: _future, builder: (ctx, snap) => ...);\n}\n```\n\n \n\n## Bestanden\n\n \n\n- ` LICENSE ` \n- ` SKILL.md ` \n- ` SOURCE.md `\n\n \n\n## Gerelateerde termen\n\n \n\n- [Dart](<https://delaparra-services.nl/nl/kennisbank/dart>) \n- [Concurrency in Dart](<https://delaparra-services.nl/nl/kennisbank/dart-concurrency>)\n\n \n\n## Gerelateerde diensten\n\n \n\n- [App-ontwikkeling](<https://delaparra-services.nl/nl/services#service-02>)\n\n \n\n[Een skill installeren in je AI-assistent](<https://delaparra-services.nl/nl/handleidingen/een-skill-installeren-in-je-ai-assistent>)\n\n[HTML version](https://delaparra-services.nl/nl/skills/flutter-concurrency)\n",
    "structured_data": {
        "@context": "https://schema.org",
        "@graph": [
            {
                "@type": "Organization",
                "@id": "https://delaparra-services.nl/#practice",
                "logo": "https://delaparra-services.nl/logo.png",
                "name": "DeLaParra Services",
                "legalName": "DeLaParra Services",
                "url": "https://delaparra-services.nl/",
                "description": "Maatwerk software, webapplicaties en mobiele apps, ontwikkeld in Laravel door één ontwikkelaar in Groningen. Vaste prijs vooraf, volledige broncode bij oplevering.",
                "email": "info@delaparra-services.nl",
                "address": {
                    "@type": "PostalAddress",
                    "addressLocality": "Groningen",
                    "addressRegion": "Groningen",
                    "addressCountry": "NL"
                },
                "areaServed": "Groningen, Nederland",
                "knowsLanguage": [
                    "en",
                    "nl"
                ],
                "knowsAbout": [
                    "Webdesign en -ontwikkeling",
                    "App-ontwikkeling",
                    "Maatwerk software en webapplicaties",
                    "OpenSpec",
                    "Beoordeling van AI-code",
                    "Je eigen programmeeragent"
                ],
                "founder": {
                    "@id": "https://delaparra-services.nl/#person"
                }
            },
            {
                "@type": "WebPage",
                "@id": "https://delaparra-services.nl/nl/skills/flutter-concurrency#webpage",
                "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency",
                "name": "Concurrency in Dart | DeLaParra Services",
                "description": "Met concurrency kan een Dart-programma voortgang maken met meerdere taken, via asynchrone operaties of isolates.",
                "isPartOf": {
                    "@id": "https://delaparra-services.nl/#website"
                },
                "about": {
                    "@id": "https://delaparra-services.nl/#practice"
                },
                "inLanguage": "nl",
                "breadcrumb": {
                    "@id": "https://delaparra-services.nl/nl/skills/flutter-concurrency#breadcrumb"
                }
            },
            {
                "@type": "BreadcrumbList",
                "@id": "https://delaparra-services.nl/nl/skills/flutter-concurrency#breadcrumb",
                "itemListElement": [
                    {
                        "@type": "ListItem",
                        "position": 1,
                        "name": "Home",
                        "item": "https://delaparra-services.nl/nl"
                    },
                    {
                        "@type": "ListItem",
                        "position": 2,
                        "name": "Concurrency in Dart"
                    }
                ]
            },
            {
                "@type": "Person",
                "@id": "https://delaparra-services.nl/#person",
                "name": "Reinier de la Parra",
                "url": "https://delaparra-services.nl/nl/about"
            },
            {
                "@type": "SoftwareSourceCode",
                "@id": "https://delaparra-services.nl/nl/skills/flutter-concurrency#skill",
                "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency",
                "name": "Concurrency in Dart",
                "description": "Met concurrency kan een Dart-programma voortgang maken met meerdere taken, via asynchrone operaties of isolates.",
                "inLanguage": "nl",
                "license": "https://spdx.org/licenses/MIT.html",
                "subjectOf": {
                    "@id": "https://delaparra-services.nl/nl/skills/flutter-concurrency#dataset"
                }
            },
            {
                "@type": "Dataset",
                "@id": "https://delaparra-services.nl/nl/skills/flutter-concurrency#dataset",
                "name": "Concurrency in Dart",
                "description": "Met concurrency kan een Dart-programma voortgang maken met meerdere taken, via asynchrone operaties of isolates.",
                "url": "https://delaparra-services.nl/nl/skills/flutter-concurrency",
                "identifier": "https://delaparra-services.nl/nl/skills/flutter-concurrency#dataset",
                "about": {
                    "@id": "https://delaparra-services.nl/nl/skills/flutter-concurrency#skill"
                },
                "creditText": "gabuldev/flutter-skills",
                "publisher": {
                    "@id": "https://delaparra-services.nl/#practice"
                },
                "license": "https://spdx.org/licenses/MIT.html",
                "isAccessibleForFree": true,
                "inLanguage": "nl",
                "dateModified": "2026-11-30T13:17:19+00:00",
                "isPartOf": {
                    "@type": "Dataset",
                    "@id": "https://delaparra-services.nl/nl/kennisbank#skills",
                    "name": "Skills voor AI-programmeerassistenten",
                    "url": "https://delaparra-services.nl/nl/kennisbank"
                },
                "includedInDataCatalog": {
                    "@type": "DataCatalog",
                    "@id": "https://delaparra-services.nl/nl/kennisbank#catalog",
                    "name": "Datacatalogus van de kennisbank",
                    "url": "https://delaparra-services.nl/nl/kennisbank"
                },
                "distribution": [
                    {
                        "@type": "DataDownload",
                        "name": "flutter-concurrency.csv",
                        "encodingFormat": "text/csv",
                        "contentUrl": "https://delaparra-services.nl/nl/skills/flutter-concurrency.csv",
                        "inLanguage": "nl",
                        "dateModified": "2026-11-30T13:17:19+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "flutter-concurrency.json",
                        "encodingFormat": "application/json",
                        "contentUrl": "https://delaparra-services.nl/nl/skills/flutter-concurrency.json",
                        "inLanguage": "nl",
                        "dateModified": "2026-11-30T13:17:19+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "flutter-concurrency.md",
                        "encodingFormat": "text/markdown",
                        "contentUrl": "https://delaparra-services.nl/nl/skills/flutter-concurrency.md",
                        "inLanguage": "nl",
                        "dateModified": "2026-11-30T13:17:19+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "flutter-concurrency.pdf",
                        "encodingFormat": "application/pdf",
                        "contentUrl": "https://delaparra-services.nl/nl/skills/flutter-concurrency.pdf",
                        "inLanguage": "nl",
                        "dateModified": "2026-11-30T13:17:19+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "flutter-concurrency.zip",
                        "encodingFormat": "application/zip",
                        "contentUrl": "https://delaparra-services.nl/nl/skills/flutter-concurrency.zip",
                        "inLanguage": "nl",
                        "dateModified": "2026-11-30T13:17:19+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "flutter-concurrency-files.zip",
                        "encodingFormat": "application/zip",
                        "contentUrl": "https://delaparra-services.nl/skills/flutter-concurrency/download",
                        "inLanguage": "nl",
                        "dateModified": "2026-11-30T13:17:19+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    }
                ]
            }
        ]
    }
}