How to create a custom plugin in Flutter ?

Kalpesh Khandla
4 min readFeb 13, 2022
How to create a custom plugin in flutter

What is Plugin ?

A plugin is a piece of software that adds capabilities to your app. For example, you might want your mobile app to interact with the camera on your device. Plugins are an important part of the flutter ecosystem. We should first check pub.dev to see if the plugin you need already exists or not ?

How to create custom plugin in flutter

Let’s move ahead with creating a package.

Flutter plugin uses a Method Channel (which acts as a bridge between iOS and Android).

Packages enable the creation of modular code that can be shared easily.

Types of packages in flutter :

There are two types of packages in the Flutter :

  1. Dart packages: General packages with only dart code (e.g. the path package)
  2. Plugin packages: Special packages that combine native code with a dart interface and allow you to use platform-specific code (e.g. the url_launcher package)

Step 1: Create the package

Step 2: Create a flutter plugin

Step 3: Flutter plugin copy and open flutter application past plugin

Step 4: Create a flutter application open the file pubspec.yaml add your plugin.

dependencies:
flutter:
sdk: fluttermy_plugin:
path: my_plugin

When the plugin has been created the default class has been generated, it contains three methods: onAttachedToEngine, onMethodCall and onDetachedFromEngine.

1) onAttachedToEngine() :
When the plugin is initialized, it creates the channel of communication with the dart part and begins to listen to the channel for messages.

2) onMethodCall() :
Whenever there’s a new message in the channel; it has 2 parameters: call which contains the details of the invocation (the method and eventual parameters) and result that will be used to send the result back to the dart part.

3) onDetachFromEngine() :
If you are creating channels in your onAttachToEngine(), there is no need to cleanup those creations in onDetachFromEngine() and creating them again the second time onAttachToEngine() is called is fine.

Method Channel: For registering the channel name.The MethodChannel that will the communication between Flutter and native Android

OnMethodCall: You have an Override method OnMethodCall. Whenever you invoke the channel, you get a call here, and it checks with the Method Name mentioned in the Flutter side and runs the set of steps appropriately.

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == “getPlatformVersion”) {
result.success(“Android ${android.os.Build.VERSION.RELEASE}”)
} else {
result.notImplemented()
}
}

Variable (MethodChannel _channel): Flutter variable in the flutter plugin for making calls to the native layer. We then need to initialize such channel. In Flutter, any channels needs to have a unique name.

registerWith(): Method to remain compatible with apps that don’t use v2 embedding. The easiest thing to do is move the logic from registerWith() into a private method that both registerWith() and onAttachedToEngine() can call if possible. Either registerWith() or onAttachToEngine() will be called, not both.

call.method: Gives the method from which it is called.

call.argument(‘argument name’): Gives the arguments we passed from dart code to the native code.

Activity (Optional): For running the screen as Activity Class Type. This is Optional if your plugin needs an Activity reference, also implement ActivityAware.

ServiceAware (Optional): If your plugin is expected to be held in a background Service at any point in time, implement ServiceAware

MainActivity.java to use the v2 embedding FlutterActivity. You may have to make a public constructor for you plugin class if one didn’t exist already.

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.firebase.core.FirebaseCorePlugin;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {

}
}

FlutterPluginBinding
-binding.getFlutterEngine(): Returns the FlutterEngine that your plugin is attached to, providing access to components like the DartExecutor, FlutterRenderer, and more.

binding.getApplicationContext(): Returns the Android application’s Context for the running app.

binding.getLifecycle(): Returns a reference that can be used to obtain a Lifecycle object. If you need to use this lifecycle reference then you need add a project dependency on Flutter’s Android lifecycle package.

ActivityAware
Activity, your ActivityAware plugin must implement appropriate behavior at 4 stages. First, your plugin is attached to an Activity. You can access that Activity and a number of its callbacks through the provided ActivityPluginBinding.

Since Activitys can be destroyed during configuration changes, you must cleanup any references to the given Activity in onDetachedFromActivityForConfigChanges(), and then re-establish those references in onReattachedToActivityForConfigChanges().

behavior and return to a non-UI configuration.

Steps For Create New Plugin

Custom Plugin in Flutter
Custom Plugin in Flutter

Thanks for being with us on a Flutter journey.

Do forget to drop me your valuable suggestion for the same.

Do not forgot to check https://github.com/Kalpesh209

Keep Fluttering !!!

--

--