Writing flutter package in an easy way
Build flutter package smoothly
I’m here to share my experience of creating a package, cause I don’t want you to get stuck in any of these creation steps, let’s understand this concept with a simple example.
Create a plugin project
Run this command to create a plugin project
flutter create --org com.example --template=plugin --platforms=android,ios -a kotlin -i swift test_project
It will create an empty project with kotlin and swift support for android and ios sides respectively.
What we get out of the box
- Android folder that contains a kotlin class, we will add all native android side code here.
- Ios folder which contains a swift class, and we will add native ios code here.
- lib folder that contains our beloved dart code.
Add plugin_platform_interface:
in pubspec.yaml file, This class package provides common functionality for platform interfaces to enforce that they are extended and not implemented.
Let’s create method calls that interacts with both the ios and android side
We’re going to add magic sdk which is available for both android and ios.
Dart side
- Let’s create an abstract class magic_platform_interface.dart it extends PlatformInterface. It contains definitions of the functions, that we need to implement.
We have added two functions definition here intializeMagic
for initializing SDK and loginWithMagicLink
to use SDK and do login.
2. We will then create a class magic_method_channel.dart which will extend our abstract class here we will write function implementation.
3. Finally we will create a class magic_flutter.dart this will be the main class that any user of this plugin will import and use all plugin functionality, we also add docs for each method, so that it’ll be easy to use for any plugin user.
That’s it for the dart side, let’s dive into the native side.
Android side
Open the Android folder in Android studio separately, it will give us essentially code completion and debug-related functionality which will be a huge time saver in long run.
- Add method calls with their respective names.
2. Define some utility methods that will be helpful to send results or error cases to the flutter side.
3. Now, we can write our method implementation for the Android side, let’s first write for intializeMagic
4. Write implementation for loginWithMagicLink
method
ios side
- Add these method calls with their respective names
2. Let’s implement initializeMagic
function on the ios side
3. Add implementation of loginWithMagicLink
function
You can check out the project and copy any part of the code, the project has complete implementation with many more functions, check it out here.
Thanks for sharing your time with me 🙌