A Wi-Fi Direct Plugin for Flutter

Overview

GitHub license Pub

flutter_p2p

A Wi-Fi Direct Plugin for Flutter.

This plugin is in alpha and only supports android at the moment.

Getting Started

Required permissions

Put this into your AndroidManifest.xml

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Request permission

In order to scan for devices and connect to devices you need to ask for the location Permission

Future<bool> _checkPermission() async {
  if (!await FlutterP2p.isLocationPermissionGranted()) {
    await FlutterP2p.requestLocationPermission();
    return false;
  }
  return true;
}

Register / unregister from WiFi events

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 _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    _register();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // Stop handling events when the app doesn't run to prevent battery draining

    if (state == AppLifecycleState.resumed) {
      _register();
    } else if (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 subscriptions
    FlutterP2p.unregister(); // Unregister from native events
  }
}

Discover devices

After you subscribed to the events you only need to call the FlutterP2p.discoverDevices() method.

List<WifiP2pDevice> _peers = [];

void _register() async {

  /// ...

  _subscriptions.add(FlutterP2p.wifiEvents.peersChange.listen((change) {
    setState(() {
      _peers = change.devices;
    });
  }));

  /// ...
}

void _discover() {
  FlutterP2p.discoverDevices();
}

Connect to a device

Call FlutterP2p.connect(device); and listen to the FlutterP2p.wifiEvents.connectionChange

 bool _isConnected = false;
 bool _isHost = false;
 String _deviceAddress = "";

 void _register() async {
    // ...

    _subscriptions.add(FlutterP2p.wifiEvents.connectionChange.listen((change) {
      setState(() {
        _isConnected = change.networkInfo.isConnected;
        _isHost = change.wifiP2pInfo.isGroupOwner;
        _deviceAddress = change.wifiP2pInfo.groupOwnerAddress;
      });
    }));

    // ...
  }

Disconnect from current P2P group

Call FlutterP2p.removeGroup()

 void _disconnect() async {
   FlutterP2p.removeGroup();
 }

Transferring data between devices

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 socket

  P2pSocket _socket;
  void _openPortAndAccept(int port) async {
    var socket = await FlutterP2p.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")` method


    print("_openPort done");

    // accept a connection on the created socket
    await FlutterP2p.acceptPort(port);
    print("_accept done");
  }

On the client:

  // Connect to the port and create a socket

  P2pSocket _socket;
  _connectToPort(int port) async {
    var socket = await FlutterP2p.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")` method

    print("_connectToPort done");
  }
Comments
  • Gradle task assembleDebug issue resolved & set min API level to 16

    Gradle task assembleDebug issue resolved & set min API level to 16

    issue : #7 #5 #18 #bug

    #7 Gradle build fails due to Kotlin gradle saying The Android Gradle plugin supports only Kotlin Gradle plugin version 1.3.10 and higher is now resolved. Accept the Pull the request please .

    #5 min sdk Version is set to API level 16.

    opened by KamleshPandey98 2
  • Migrated plugin and example to AndroidX.

    Migrated plugin and example to AndroidX.

    Fixed AndroidX and Kotlin version error. Error for Discover method still exists (But note that i tried on emulator so maybe it's because of that. Will try with actual device.)

    p.s. Not sure if all this .xml files are necessary but Android Studio generated them while migrated to AndroidX.

    opened by SteffNite 2
  • Adds discovery change events

    Adds discovery change events

    Hi Julian. Got another one if you are interested. This PR exposes the WIFI_P2P_DISCOVERY_CHANGED_ACTION events. I use these to do things like automatically call discover peers again if the discovery period times out if the user does not connect to a device.

    • Adds a new message type DiscoveryStateChange to protos
    • Registers the WIFI_P2P_DISCOVERY_CHANGED_ACTION with the Broadcast receiver
    • Adds a new EventChannel for the new event type
    enhancement 
    opened by qwales1 2
  • Failed to handle method call

    Failed to handle method call

    Failed to handle method call E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): java.lang.IllegalArgumentException: Unsupported value: java.lang.reflect.InvocationTargetException E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:278) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at io.flutter.plugin.common.StandardMethodCodec.encodeErrorEnvelope(StandardMethodCodec.java:69) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler$1.error(MethodChannel.java:236) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at de.mintware.flutter_p2p.FlutterP2pPlugin.onMethodCall(FlutterP2pPlugin.kt:352) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at android.os.MessageQueue.nativePollOnce(Native Method) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at android.os.MessageQueue.next(MessageQueue.java:325) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at android.os.Looper.loop(Looper.java:142) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at android.app.ActivityThread.main(ActivityThread.java:6528) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at java.lang.reflect.Method.invoke(Native Method) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) E/MethodChannel#de.mintware.flutter_p2p/flutter_p2p(13511): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

    opened by JAICHANGPARK 1
  • Enhancement Example App

    Enhancement Example App

    Enhancement

    • 86b6eb5 Block mutiple open socket

    Update

    • 4b5c0d9 Update UI Raised Button to List Tile in Example App
    • 41014fe Update snackbar text in steam

    Fixed

    • 028f1a3 Fix Location of Variables
    • 86c20e9 Fixed Send Hello Button after disconnect state
    opened by JAICHANGPARK 1
  • Adds call to WifiP2pManager.removeGroup to disconnect

    Adds call to WifiP2pManager.removeGroup to disconnect

    First off, thanks for this plugin. Its awesome!

    This PR adds a call to WifiP2pManager.removeGroup to be able to disconnect from the currently connected P2P group. I am brand new to Flutter and also Kotlin so if anything is not looking right please let me know and I can fix. I updated the example app with a "Disconnect" button so you can try it out.

    enhancement 
    opened by qwales1 1
  • Code cleanup

    Code cleanup

    • Created a ResultActionListener which implements the WifiP2pManager.ActionListener to remove duplicate code.
    • Removed redundant semicolons
    • Removed unused code
      • EventChannelPool.unregister()
    • Changelog updated
    enhancement 
    opened by devtronic 0
  • Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file.

    Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file.

    Hello Now I have some problem about pub get process

    Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file. An instruction to format the `pubspec.yaml` can be found here:
    
    opened by JAICHANGPARK 3
  • project ':flutter_p2p' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71

    project ':flutter_p2p' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71

    FAILURE: Build failed with an exception.

    • What went wrong: The Android Gradle plugin supports only Kotlin Gradle plugin version 1.3.0 and higher. The following dependencies do not satisfy the required version: project ':flutter_p2p' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71

    • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

    I have upgraded flutter to the latest version.Plz help me.

    flutter doctor -v image

    opened by Megatron-Siva 5
  • Mismatch in the repository example and pub.dev example

    Mismatch in the repository example and pub.dev example

    The example given on the package page does not match the example code mentioned in the repository. The example on the pub.dev page doesn't work either. It should be updated to reflect the latest, working example.

    opened by prakharb10 0
  • Gradle Support for 1.3.10 and above

    Gradle Support for 1.3.10 and above

    I'm getting this error while building the app. FAILURE: Build failed with an exception.

    • What went wrong: The Android Gradle plugin supports only Kotlin Gradle plugin version 1.3.10 and higher. The following dependencies do not satisfy the required version: project ':flutter_p2p' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71
    opened by JICA98 3
Releases(v0.1.1)
Owner
mintware
mintware
Get It - Simple direct Service Locator that allows to decouple the interface from a concrete implementation and to access the concrete implementation from everywhere in your App. Maintainer: @escamoteur

❤️ Sponsor get_it This is a simple Service Locator for Dart and Flutter projects with some additional goodies highly inspired by Splat. It can be used

Flutter Community 1k Jan 1, 2023
This is just the simplyfied Flutter Plugin use for one of the popular flutter plugin for social media login.

social_media_logins Flutter Plugin to login via Social Media Accounts. Available Social Media Logins: Facebook Google Apple Getting Started To use thi

Reymark Esponilla 3 Aug 24, 2022
Permission plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to request and check permissions.

Flutter permission_handler plugin The Flutter permission_handler plugin is build following the federated plugin architecture. A detailed explanation o

Baseflow 1.7k Dec 31, 2022
Unloc customizations of the Permission plugin for Flutter. This plugin provides an API to request and check permissions.

Flutter Permission handler Plugin A permissions plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to request and check perm

Unloc 1 Nov 26, 2020
Klutter plugin makes it possible to write a Flutter plugin for both Android and iOS using Kotlin only.

The Klutter Framework makes it possible to write a Flutter plugin for both Android and iOS using Kotlin Multiplatform. Instead of writing platform spe

Gillian 33 Dec 18, 2022
A Flutter step_tracker plugin is collect information from user and display progress through a sequence of steps. this plugin also have privilege for fully customization from user side. like flipkart, amazon, myntra, meesho.

step_tracker plugin A Flutter step_tracker plugin is collect information from user and display progress through a sequence of steps. this plugin also

Roshan nahak 5 Oct 21, 2022
Boris Gautier 1 Jan 31, 2022
A Side Menu plugin for flutter and compatible with liquid ui for flutter

Liquid Shrink Side Menu A Side Menu plugin for flutter and compatible with liquid ui Side Menu Types There are 8 configuration of Liquid shrink side m

Raj Singh 18 Nov 24, 2022
FlutterBoost is a Flutter plugin which enables hybrid integration of Flutter for your existing native apps with minimum efforts

中文文档 中文介绍 Release Note v3.0-preview.17 PS: Before updating the beta version, please read the CHANGELOG to see if there are any BREAKING CHANGE Flutter

Alibaba 6.3k Dec 30, 2022
Flutter Counter is a plugin written in dart for flutter which is really simple and customizeable.

Flutter Counter (iOS & Android) Description Flutter Counter is a plugin written in dart for flutter which is really simple and customizeable. Create i

Salmaan Ahmed 15 Sep 18, 2022
Flutter simple image crop - A simple and easy to use flutter plugin to crop image on iOS and Android

Image Zoom and Cropping plugin for Flutter A simple and easy used flutter plugin to crop image on iOS and Android. Installation Add simple_image_crop

null 97 Dec 14, 2021
Flutter-ffmpeg - FFmpeg plugin for Flutter. Not maintained anymore. Superseded by FFmpegKit.

flutter_ffmpeg FFmpeg plugin for Flutter. Supports iOS and Android. Not maintained anymore, superseded by FFmpegKit. See FlutterFFmpeg to FFmpegKit Mi

Taner Şener 635 Dec 22, 2022
Rave flutter - A Flutter plugin for Flutterwaves's rave.

Rave Flutter A robust Flutter plugin for accepting payment on Rave with Card Nigerian Bank Account ACH Payments Mobile money Francophone Africa Mpesa

Wilberforce Uwadiegwu 30 Oct 6, 2022
A flutter plugin to add login with facebook in your flutter app

Features Login on iOS, Android and Web. Express login on Android. Granted and declined permissions. User information, picture profile and more. Provid

Darwin Morocho 157 Jan 6, 2023
Flutter blue plus - Flutter plugin for connecting and communicationg with Bluetooth Low Energy devices, on Android and iOS

Introduction FlutterBluePlus is a bluetooth plugin for Flutter, a new app SDK to

null 141 Dec 22, 2022
This is a Flutter plugin that takes a JSON string and converts it onto a customizable Flutter Widget.

Colored JSON Convert JSON string into customizable widget. Getting Started ColoredJson is a stateless widget that produces a structured view of JSON s

null 4 May 20, 2022
Flutter plugin to manage home screen widget within flutter app.

Flutter App Widget App Widget / Home Screen widget plugin for flutter app Usage Please see app_widget subdirectory for the usage documentation. Plafor

Alexander Dischberg 6 Dec 16, 2022
Flutter plugin for creating static & dynamic app shortcuts on the home screen.

Flutter Shortcuts Show some ❤️ and ⭐ the repo Why use Flutter Shortcuts? Flutter Shortcuts Plugin is known for : Flutter Shortcuts Fast, performant &

Divyanshu Shekhar 39 Sep 26, 2022