Orientação gerada a partir de informações públicas. Apenas para referência.
flutter_p2p é um plugin Flutter que habilita a conectividade WiFi Direct em dispositivos Android usando a API nativa de WiFi P2P da plataforma. Ele permite que aplicativos descubram e se conectem diretamente a dispositivos próximos via WiFi sem exigir um ponto de acesso central. Isso é ideal para compartilhamento de arquivos ponto a ponto, comunicação em tempo real ou colaboração entre dispositivos locais. O plugin fornece uma interface simples para gerenciar conexões, escanear pares e transferir dados. É especificamente projetado para Android e não suporta iOS ou outras plataformas.
Casos de uso
Transferência direta de arquivo entre dispositivos
jogos multijogador locais
Sincronização de dados offline
pareamento de dispositivo IoT
Compartilhamento de dados de sensores em tempo real
Principais recursos
Integração nativa do WiFi P2P do Android
Descoberta de dispositivos e gerenciamento de conexões
Comunicação ponto a ponto segura
API simples do Dart
Implementação específica da plataforma
Indicado para
Aplicativos exclusivos para Android
Comunicação de rede local
Interação de dispositivo com baixa latência
Aplicativos que precisam de links diretos ao dispositivo
Projetos evitando infraestrutura centralizada
Considerações
Funciona apenas no Android
Requer permissões de WiFi P2P
Limitado ao intervalo da rede local
Sem suporte para iOS
Depende da compatibilidade de hardware do dispositivo
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
flutter_p2p
A Wi-Fi Direct Plugin for Flutter.
This plugin is in alpha and only supports android at the moment.
To receive notifications for connection changes or device changes (peers discovered etc.) you have
to subscribe to the wifiEvents and register the plugin to the native events.
class_MyAppStateextendsState<MyApp> withWidgetsBindingObserver{
@overridevoidinitState() {
super.initState();
_register();
WidgetsBinding.instance.addObserver(this);
}
@overridevoiddispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@overridevoiddidChangeAppLifecycleState(AppLifecycleState state) {
// Stop handling events when the app doesn't run to prevent battery drainingif (state == AppLifecycleState.resumed) {
_register();
} elseif (state == AppLifecycleState.paused) {
_unregister();
}
}
List<StreamSubscription> _subscriptions = [];
void_register() async {
if (!await_checkPermission()) {
return;
}
_subscriptions.add(FlutterP2p.wifiEvents.stateChange.listen((change) {
// Handle wifi state change
}));
_subscriptions.add(FlutterP2p.wifiEvents.connectionChange.listen((change) {
// Handle changes of the connection
}));
_subscriptions.add(FlutterP2p.wifiEvents.thisDeviceChange.listen((change) {
// Handle changes of this device
}));
_subscriptions.add(FlutterP2p.wifiEvents.peersChange.listen((change) {
// Handle discovered peers
}));
_subscriptions.add(FlutterP2p.wifiEvents.discoveryChange.listen((change) {
// Handle discovery state changes
}));
FlutterP2p.register(); // Register to the native events which are send to the streams above
}
void_unregister() {
_subscriptions.forEach((subscription) => subscription.cancel()); // Cancel subscriptionsFlutterP2p.unregister(); // Unregister from native events
}
}
Discover devices
After you subscribed to the events you only need to call the FlutterP2p.discoverDevices() method.
After you are connected to a device you can transfer data async in both directions (client -> host, host -> client).
On the host:
// Open a port and create a socketP2pSocket _socket;
void_openPortAndAccept(int port) async {
var socket = awaitFlutterP2p.openHostPort(port);
setState(() {
_socket = socket;
});
var buffer = "";
socket.inputStream.listen((data) {
var msg = String.fromCharCodes(data.data);
buffer += msg;
if (data.dataAvailable == 0) {
_showSnackBar("Data Received: $buffer");
buffer = "";
}
});
// Write data to the client using the _socket.write(UInt8List) or `_socket.writeString("Hello")` methodprint("_openPort done");
// accept a connection on the created socketawaitFlutterP2p.acceptPort(port);
print("_accept done");
}
On the client:
// Connect to the port and create a socketP2pSocket _socket;
_connectToPort(int port) async {
var socket = awaitFlutterP2p.connectToHost(
_deviceAddress, // see above `Connect to a device`
port,
timeout: 100000, // timeout in milliseconds (default 500)
);
setState(() {
_socket = socket;
});
var buffer = "";
socket.inputStream.listen((data) {
var msg = String.fromCharCodes(data.data);
buffer += msg;
if (data.dataAvailable == 0) {
_showSnackBar("Received from host: $buffer");
buffer = "";
}
});
// Write data to the host using the _socket.write(UInt8List) or `_socket.writeString("Hello")` methodprint("_connectToPort done");
}