Building a Napacitor Plugin
Napacitor provides a comprehensive Plugin API to use when adding native functionality to a Napacitor app.
There are two types of Napacitor plugins: a local plugin is custom C# code isolated to a particular Napacitor application, residing within the maui/ project committed as part of source control. A global plugin is a published npm package that developers can add to any Napacitor application.
In this tutorial, we will start with a blank Napacitor application and add native code to it to build a local plugin. Then we will package it up into a global plugin, ready to be published.
So, what are we going to build?
Pretend that you work for a delivery carrier, and the application you wrote lets drivers obtain signatures from customers, confirming they have received their deliveries. The user interface looks completely different in portrait versus landscape mode, so the app needs to know the device's current orientation and react whenever it changes.
The plugin we build will implement screen orientation features to accommodate this request:
- The device's current orientation will be detected, with differing UIs for portrait and landscape mode.
- Listeners will be notified whenever the screen orientation changes.
For this tutorial, we will mock up a signature pad but only build out screen orientation functionality.
This ScreenOrientation plugin will work across the web, Android, iOS, macOS, and Windows platforms — a single C# class runs everywhere, because the native layer is a .NET MAUI Blazor host.
Note: unlike Capacitor's screen orientation tutorial, this one does not implement
lock()/unlock(). .NET MAUI does not offer a cross-platform API for programmatically locking the orientation; apps typically fix the orientation of specific pages via platform configuration instead.
Getting started
Create a new Napacitor app:
npx @napacitor/cli init delivery-app com.example.delivery
cd delivery-app
npm install
npm run build
npx nap add maui
nap init scaffolds the web app and napacitor.config.json; nap add maui generates the maui/ host project that the C# plugin code will live in.
This tutorial uses plain TypeScript for the UI. If you are not familiar with the framework concepts covered, that's OK! The plugin concepts apply to Napacitor apps using any TypeScript-enabled web framework.
Now that we have a Napacitor app in place with the MAUI host added, we're ready to move on to the first step of building a plugin: designing the API.