flutter/flutter-interoperating-with-native-apis

Interopera com APIs de plataforma nativa no Android, iOS e na web. Use ao acessar recursos específicos do dispositivo não disponíveis em Dart ou ao chamar código nativo existente.

O que é flutter-interoperating-with-native-apis?

Esta habilidade permite que desenvolvedores Flutter se integrem com APIs nativas de plataforma no Android, iOS e web, acessando funcionalidades específicas do dispositivo que não estão disponíveis diretamente em Dart. Ela suporta plataformas Android, iOS e web, permitindo a invocação de código nativo existente ou o acesso a recursos como sensores, câmera, armazenamento e muito mais. Através do uso de canais de método (Method Channels) no Android/iOS e do pacote `js` para web, a habilidade facilita a comunicação bidirecional entre o Dart e o código nativo (Kotlin/Java para Android, Swift/Objective-C para iOS, JavaScript para web). É essencial para projetos que precisam estender as capacidades do Flutter além do que as bibliotecas nativas oferecem, mantendo uma arquitetura limpa e organizada.

Funciona com~Claude Code~Codex CLI~Cursor
Part ofMobile
npx skills add https://github.com/flutter/skills/tree/main/skills/flutter-interoperating-with-native-apis

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

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

Documentação

O que flutter-interoperating-with-native-apis faz?

Interopera com APIs de plataforma nativa no Android, iOS e na web. Use ao acessar recursos específicos do dispositivo não disponíveis em Dart ou ao chamar código nativo existente.

Visão Geral

Esta habilidade fornece mecanismos para que aplicativos Flutter se comuniquem com código nativo das plataformas alvo, permitindo acesso a funcionalidades como câmera, sensores, armazenamento local, e muito mais.

Plataformas Suportadas

  • Android: Kotlin/Java via Android Method Channels
  • iOS: Swift/Objective-C via Flutter Method Channels
  • Web: JavaScript via pacote js

Como Funciona

Method Channels

Os Method Channels permitem que o Dart envie mensagens para o lado nativo e receba respostas de forma assíncrona.

Exemplo no Dart:

import 'package:flutter/services.dart';

static const platform = MethodChannel('com.example/native');

Future<String> getBatteryLevel() async {
  try {
    final result = await platform.invokeMethod('getBatteryLevel');
    return 'Battery level: $result%';
  } on PlatformException catch (e) {
    return 'Failed to get battery level: ${e.message}';
  }
}

Exemplo no Android (Kotlin):

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.example/native"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
            call, result ->
            if (call.method == "getBatteryLevel") {
                val batteryLevel = getBatteryLevel()
                if (batteryLevel != -1) {
                    result.success(batteryLevel)
                } else {
                    result.error("UNAVAILABLE", "Battery level not available.", null)
                }
            } else {
                result.notImplemented()
            }
        }
    }

    private fun getBatteryLevel(): Int {
        val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
        return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
    }
}

Exemplo no iOS (Swift):

import Flutter
import UIKit

public class SwiftFlutterPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "com.example/native", binaryMessenger: registrar.messenger())
        let instance = SwiftFlutterPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if call.method == "getBatteryLevel" {
            let batteryLevel = UIDevice.current.batteryLevel * 100
            if batteryLevel >= 0 {
                result(Int(batteryLevel))
            } else {
                result(FlutterError(code: "UNAVAILABLE", message: "Battery level not available.", details: nil))
            }
        } else {
            result(FlutterMethodNotImplemented)
        }
    }
}

Exemplo na Web (JavaScript):

// arquivo: web/index.html
<script>
  window.flutter_inappwebview = {
    callHandler: function(handlerName, ...args) {
      return window.flutter_inappwebview.callHandler(handlerName, ...args);
    }
  };

  function getBatteryLevel() {
    // Lógica nativa da web
    return 75;
  }
</script>

Melhores Práticas

  • Tratamento de Erros: Sempre implemente tratamento adequado de erros nos Method Channels para evitar que exceções não tratadas quebrem o aplicativo.
  • Tipos de Dados: Use tipos de dados suportados (String, int, double, bool, List, Map) para serialização através dos canais.
  • Desempenho: Mantenha as operações nativas leves para não bloquear a thread principal do Dart.
  • Testes: Utilize testes unitários e de widget para simular as chamadas de canal.

Links Relacionados

Contribuições

Sinta-se à vontade para contribuir com melhorias e exemplos adicionais através de pull requests.

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