Flutter native event call | Flutter Event Call


To invoke a native method you need 4 simple steps only

 

Step 1- You can call this method from init method of your screen


@override
void initState() {
   super.initState();
   new DeviceEventChannel(deviceStateChangeCallback).registerDeviceChangeListener(deviceId);
}

@override
void dispose() {
  new DeviceEventChannel(deviceStateChangeCallback).unRegisterDeviceChangeListener();
  super.dispose();
}

deviceStateChangeCallback() async {
  ///Action Event callback
}



Step 2- For native event call first you need to create a class in lib folder of your plugin and initiate a EventChannel.


class DeviceEventChannel{
  static const _registerHomeStream = const EventChannel("device_event");
  final dynamic _deviceStateChangeCallback;
  static StreamSubscription _deviceEventSubscription;

   DeviceEventChannel(this._deviceStateChangeCallback);

  /// Subscribe the event stream
   void registerDeviceChangeListener(String deviceId) async {
    if (_deviceEventSubscription == null && await ( _initDevice(deviceId))) {
      _deviceEventSubscription = _registerHomeStream.receiveBroadcastStream().listen(onDeviceStatusChanged);
    }
    print("Device event listning start");
   }

   void unRegisterDeviceChangeListener() {
    if (_deviceEventSubscription != null) {
      _deviceEventSubscription = _registerHomeStream.receiveBroadcastStream().listen(onEventSubscriptionRemoved);
      _deviceEventSubscription.cancel();
      _deviceEventSubscription = null;
    }
  }


  onDeviceStatusChanged(dynamic params) {
    _deviceStateChangeCallback();
  }

  onEventSubscriptionRemoved(dynamic params) {
    print("Device event listning stopped");
  }
}

 

Step 3- Now Create another class in your native Android src.main folder where you need to implement MethodCallHandler


public class CloudSdkPlugin implements MethodCallHandler {
  public static void registerWith(Registrar registrar) {
    EventChannel deviceEventRegisterService = new EventChannel(registrar.messenger(),"device_event" );
    deviceEventRegisterService.setStreamHandler(new DeviceEventHandler());
  }
}


Step 4- Now implement EventChannel.StreamHandler


public class DeviceEventHandler implements EventChannel.StreamHandler {
  @Override
  public void onListen(Object o, final EventChannel.EventSink eventSink) {
    Log.e("Success", "listener");
     eventSink.success(true);//Listener
  }

  @Override
    public void onCancel(Object o) {
        Log.e("Error", "cancelling listener");
    }
}




Previous
Next Post »