EasyCord LogoDocs
Guides

Writing Custom Flutter Plugins

Create custom Dart plugins and expose them to your web frontend.

Introduction

EasyCord allows you to write custom Swift, Kotlin, or Dart code and call it from JavaScript. You can wrap any package from pub.dev and expose its functionality directly to your web application.

Prerequisites

  • Basic knowledge of Dart and Flutter.
  • An existing EasyCord project.

Step 1: Create the Plugin Class

Create a class that implements EasyCordPlugin. Register your methods and streams inside the registerWith method.

import 'package:easycord/easycord.dart';
import 'package:battery_plus/battery_plus.dart';

class MyBatteryPlugin implements EasyCordPlugin {
  final Battery _battery = Battery();

  @override
  void registerWith(EasyCordBridge bridge) {
    bridge.register('custom_getBatteryLevel', (args) async {
      final level = await _battery.batteryLevel;
      return {'level': level};
    });

    bridge.registerStream('custom_watchBatteryState', (args, sendEvent) {
      final subscription = _battery.onBatteryStateChanged.listen((state) {
        sendEvent({'state': state.toString()});
      });
      return () => subscription.cancel();
    });
  }
}

Step 2: Initialize the Plugin

Pass your custom plugin into the plugins array when initializing EasyCord.

import 'package:flutter/material.dart';
import 'package:easycord/easycord.dart';
import 'my_battery_plugin.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await EasyCord.initialize(
    plugins: [
      EasyCordDialogs(),
      EasyCordHaptics(),
      MyBatteryPlugin(),
    ],
  );

  runApp(const MyApp());
}

Step 3: Whitelist the Methods

Add the exact method names you registered to your easycord_permissions.yaml file.

permissions:
  - "dialogs_alert"
  - "custom_getBatteryLevel"
  - "custom_watchBatteryState"

Step 4: Call from JavaScript

Call the registered methods directly from your web application using the EasyCord API.

async function checkBattery() {
  const result = await window.easycord.call('custom_getBatteryLevel');
  console.log("Battery is at:", result.level);
}

function watchBattery() {
  const streamId = window.easycord.stream('custom_watchBatteryState', {}, (error, data) => {
    console.log("Battery state changed to:", data.state);
  });
  return streamId;
}

Verification

Call checkBattery() in your JavaScript console. The console logs the current battery level of the device.

Troubleshooting

Method Not Found Error

Occurs when the JavaScript calls a method that is not registered or not whitelisted. Verify that the method name matches exactly in the Dart class, the JavaScript call, and the easycord_permissions.yaml file.

Next Steps