Skip to content

Protoss78/nearby_connections

Repository files navigation

nearby_connections

A Flutter plugin for the Nearby Connections API. Inspired and partially forked from nearby-connectivity.

IMPORTANT:

  • Only Android side is implemented so far.
  • Any help regarding an iOS adaptation would be very much appreciated.
  • Also FILE and STREAM payloads are not supported yet. Only BYTE payloads can be exchanged at the moment.

Getting Started

Import package

import 'package:nearby_connections/nearby_connections.dart';

Start advertising

NearbyConnections.startAdvertising(strategy: Strategy.P2P_CLUSTER, name: myName, idService: MY_SERVICE_ID);

Listen for connection requests and auto accept them

NearbyConnections.getConnectionLifecycleStream().listen((connection) { 
  switch (advertise.type) {
    case TypeLifecycle.initiated:
      // accept connection here
      NearbyConnections.acceptConnection(connection.lifecycle.idEndpoint);
      break;
    case TypeLifecycle.result:
      break;
    case TypeLifecycle.disconnected:
      // you are now disconnected
      break;
  }
});
NearbyConnections.startAdvertising(strategy: Strategy.P2P_CLUSTER, name: myName, idService: MY_SERVICE_ID);

Start discovery

NearbyConnections.startDiscovery(strategy: Strategy.P2P_CLUSTER, idService: MY_SERVICE_ID);

Listen for discovered connections

NearbyConnections.getDiscoveryStream().listen((discovery) { 
  if (discovery.type == TypeDiscovery.found) {
    // New advertiser discovered
  } else if (discovery.type == TypeDiscovery.lost) {
    // Advertised connection was lost
  }
});

Reject a connection

NearbyConnections.rejectConnection(endpointId);

Send a payload to a single endpoint

const Utf8Encoder encoder = Utf8Encoder();
NearbyConnections.sendPayloads(receiverEndpointId, encoder.convert(value.toString()));

Send a payload to multiple endpoints

const Utf8Encoder encoder = Utf8Encoder();
NearbyConnections.sendPayloads(receiverEndpointIdList, encoder.convert(value.toString()));

Handle incoming payloads

const Utf8Decoder decoder = Utf8Decoder();
NearbyConnections.getPayloadStream().listen((payload) {
  String textValue = decoder.convert(payload.bytes);
});

Stop advertising

NearbyConnections.stopAdvertising();

Stop discovery

NearbyConnections.stopDiscovery();

Disconnect a single endpoint

NearbyConnections.disconnectFromEndpoint(endpointId);

Stop all connections

NearbyConnections.stopAllEndpoints();

About

A Flutter plugin for the Nearby Connections API

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published