Communitygithub.com

flutter/flutter-handling-concurrency

Executa tarefas de longa duração em isolates em segundo plano para manter a IU responsiva. Use ao realizar cálculos pesados ou analisar grandes conjuntos de dados.

O que é flutter-handling-concurrency?

Esta skill do Flutter lida com concorrência usando isolates para executar tarefas demoradas sem travar a interface do usuário. Ela é útil para operações intensivas de CPU, como processamento de dados, análise de JSON ou cálculos complexos, onde você precisa manter a IU suave e responsiva. A skill demonstra como criar um isolate separado, enviar mensagens para ele e recuperar resultados de forma assíncrona usando `Isolate.spawn` e `ReceivePort`. Também aborda o uso de `compute` do Flutter para simplificar o processo, especialmente quando a tarefa é auto-contida e não requer comunicação bidirecional contínua. O agente pode aplicar esse padrão para garantir que operações pesadas não bloqueiem a thread principal da IU, melhorando a experiência do usuário em aplicativos Flutter.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/flutter/skills/tree/main/skills/flutter-handling-concurrency

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que flutter-handling-concurrency faz?

Executa tarefas de longa duração em isolates em segundo plano para manter a IU responsiva. Use ao realizar cálculos pesados ou analisar grandes conjuntos de dados.

Como Usar

Criando e Usando um Isolate

  1. Defina uma função de longa duração que será executada no isolate.
  2. Use Isolate.spawn para criar um novo isolate e executar a função.
  3. Configure um ReceivePort para receber mensagens do isolate.
  4. Encerre o isolate quando não for mais necessário.

Exemplo

import 'dart:isolate';
import 'package:flutter/foundation.dart';

// Função pesada que será executada em um isolate
void heavyComputation(SendPort sendPort) {
  // Simulação de processamento intensivo
  double resultado = 0;
  for (int i = 0; i < 1000000; i++) {
    resultado += i * 0.5;
  }
  sendPort.send(resultado);
}

// Na sua UI
Future<void> performInBackground() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(heavyComputation, receivePort.sendPort);

  final resultado = await receivePort.first;
  print('Resultado: $resultado');
  
  // Opcional: encerrar o isolate explicitamente
  // receivePort.close();
}

Usando compute (Forma Simplificada)

Se a tarefa for auto-contida e não precisar de comunicação contínua, use compute:

Future<void> performWithCompute() async {
  final resultado = await compute(heavyComputation, null);
  print('Resultado: $resultado');
}

Boas Práticas

  • Use compute sempre que possível para simplificar.
  • Para comunicação bidirecional ou tarefas contínuas, prefira Isolate.spawn e ReceivePort.
  • Evite passar muitos dados grandes entre isolates; prefira referências ou arquivos.
  • Sempre encerre isolates quando não forem mais necessários para liberar recursos.
  • Teste o desempenho para garantir que a concorrência realmente melhora a experiência.

Notas

  • Isolates não compartilham memória, então toda comunicação é baseada em mensagens.
  • compute é limitado a funções que recebem um único argumento e retornam um valor.
  • Para tarefas com múltiplos argumentos ou estados compartilhados, implemente seu próprio isolate com lógica de mensagens.

Referências

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

flutter/flutter-accessibility

Configure your Flutter app to support assistive technologies like Screen Readers

flutter/flutter-accessibility-audit

Triggers an accessibility scan through the widget_inspector and automatically adds Semantics widgets or missing labels to the source code.

flutter/flutter-adding-home-screen-widgets

Adds home screen widgets to a Flutter app for Android and iOS. Use when providing glanceable app information or quick actions on the device home screen.

flutter/flutter-add-integration-test

Configures Flutter Driver for app interaction and converts MCP actions into permanent integration tests. Use when adding integration testing to a project, exploring UI components via MCP, or automating user flows with the integration_test package.

flutter/flutter-add-widget-preview

Adds interactive widget previews to the project using the previews.dart system. Use when creating new UI components or updating existing screens to ensure consistent design and interactive testing.

flutter/flutter-add-widget-test

Implement a component-level test using `WidgetTester` to verify UI rendering and user interactions (tapping, scrolling, entering text). Use when validating that a specific widget displays correct data and responds to events as expected.

flutter/flutter-animating-apps

Implements animated effects, transitions, and motion in a Flutter app. Use when adding visual feedback, shared element transitions, or physics-based animations.

flutter/flutter-animation

Add animated effects to your Flutter app

flutter/flutter-apply-architecture-best-practices

Architects a Flutter application using the recommended layered approach (UI, Logic, Data). Use when structuring a new project or refactoring for scalability.

flutter/flutter-app-size

Measure and reduce the size of the Flutter app bundle, APK, or IPA

flutter/flutter-architecting-apps

Architects a Flutter application using the recommended layered approach (UI, Logic, Data). Use when structuring a new project or refactoring for scalability.

flutter/flutter-architecture

Use the Flutter team's recommended app architecture

flutter/flutter-building-forms

Builds Flutter forms with validation and user input handling. Use when creating login screens, data entry forms, or any multi-field user input.

flutter/flutter-building-layouts

Builds Flutter layouts using the constraint system and layout widgets. Use when creating or refining the UI structure of a Flutter application.

flutter/flutter-building-plugins

Builds Flutter plugins that provide native interop for other apps to use. Use when creating reusable packages that bridge Flutter with platform-specific functionality.

flutter/flutter-build-responsive-layout

Use `LayoutBuilder`, `MediaQuery`, or `Expanded/Flexible` to create a layout that adapts to different screen sizes. Use when you need the UI to look good on both mobile and tablet/desktop form factors.

flutter/flutter-caching

Cache data in a Flutter app

flutter/flutter-caching-data

Implements caching strategies for Flutter apps to improve performance and offline support. Use when retaining app data locally to reduce network requests or speed up startup.

flutter/flutter-concurrency

Execute long-running tasks in a background thread in Flutter

flutter/flutter-databases

Work with databases in a Flutter app

Habilidades Relacionadas