There are so many useful Flutter plugins on pub.dev official flutter package and plugins website. Sometimes we need to create our own plugin according to our project needs. In this post, I'll show you step by step process of how you can make your own Flutter plugin.
Package vs Plugin
Plugin and package are not the same things. Plugins are dependent on the platform-specific code. In simple words, the package doesn't contain any platform-specific code and it can be used for any flutter project, on the other hand, plugins are tightly coupled with platform-specific code.
In this post, I'll show you a step by step process for creating an android plugin for the flutter project with java code implementation. You can add more platforms you need according to your project demand. You will find more info about flutter plugin development on the official flutter website.
Create a directory in your backup drive where you want to keep your own plugins. An example is given below.
D:/flutter/projects - here are all our flutter project
D:/flutter/plugins - here are all our developed packages or plugins. So we can reuse it in our multiple projects.
flutter create --org com.flutter-tutorial --template=plugin --platforms=android -a java my_plugin
At the end of the command my_plugin
is our plugin name. Change it with your plugin name. --org
you can use your own domain name.
Open the my_plugin.dart
file from the lib directory.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';
class MyPlugin {
static const MethodChannel _channel = const MethodChannel('my_plugin');
static Future<String> get platformVersion async {
final String? version = await _channel.invokeMethod('getPlatformVersion');
return version;
}
static Future<dynamic> getDeviceInfo() async {
var result = await _channel.invokeMethod('getDeviceInfo');
return jsonDecode(result);
}
}
Here we only added a method named getDeviceInfo
for fetching the device information of our android device. Later we'll implement the getDeviceInfo
method on the java android side.
Here we are implementing only android platform code, so open the MyPlugin.java file from the android\src\main\java\com\fluttertutorial\my_plugin
directory.
package com.fluttertutorial.my_plugin;
import android.os.Build;
import org.json.JSONObject;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
public class MyPlugin implements FlutterPlugin, MethodCallHandler {
private MethodChannel channel;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "my_plugin");
channel.setMethodCallHandler(this);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
}
if (call.method.equals("getDeviceInfo")) {
result.success(getDeviceInfo());
}
else {
result.notImplemented();
}
}
public String getDeviceInfo() {
try {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
String sdkVersion = Build.VERSION.SDK;
String osVersion = Build.VERSION.RELEASE;
JSONObject obj = new JSONObject();
obj.put("platform", "android");
obj.put("model", model);
obj.put("manufacturer", manufacturer);
obj.put("os_version", osVersion);
obj.put("sdk_version", sdkVersion);
return obj.toString();
} catch (Exception e) {
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
}
Our flutter plugin is ready to use. We can add more property, methods according to our needs. Let's see how you can use it on our flutter application.
According to our tutorial post, we created our plugins into D:/flutter/plugins
and flutter projects are into D:/flutter/projects
.
Our plugin name was my_plugin
so we can use it to our any project by adding these lines into the project's pubspec.yml
file.
my_plugin:
path: ../plugins/my_plugin
Usages
import 'package:my_plugin/my_plugin.dart';
static Future<dynamic> getDeviceInfo() async {
var result = await MyPlugin.getDeviceInfo()
print(result);
print(result['model']);
}
@override
void initState() {
super.initState();
getDeviceInfo();
}
If you need activity.startActivityForResult
and onActivityResult
, you have to implement ActivityAware, PluginRegistry.ActivityResultListener
to your plugin class.
public class MyPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.ActivityResultListener
{
Context context;
Activity activity;
private MethodChannel.Result pendingResult;
@Override
public void onMethodCall(@NonNull final MethodCall call, @NonNull Result result) {
pendingResult = result;
//your codes
}
onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding){
context = flutterPluginBinding.getApplicationContext();
}
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
activity = binding.getActivity();
binding.addActivityResultListener(this);
}
@Override
public boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// do your code
// you can send result from here by pendingResult.success
return false;
}
}
Hope this step by step tutorial post will help you to make your flutter plugin. If you find this tutorial post helpful then please share it with others.