This article mainly introduces how to develop the Android part of Flutter Plugin. Regarding the concepts of Flutter and Flutter Plugin, those interested can view relevant information from the official website.
1. Introduction
The author's development environment is Android Studio under Mac. AS is also officially recommended by Google. After installing the flutter plug-in, development is much more convenient than other IDEs. It comes with three templates:
- Flutter Application: Flutter application
- Flutter Plugin:Flutter插件 Flutter
- Package: pure Dart component
Plugin is actually a special Package. Flutter Plugin provides the underlying encapsulation of Android or iOS and provides component functions on the Flutter layer, allowing Flutter to more easily access Native modules. Many platform dependencies or parts that are more complex to implement in Flutter can be encapsulated into Plugins. The principle is as follows:
Messages are carried between client and host through platform channels, and the communication between them is asynchronous.
2. Create components
Create a new Flutter Plugin project directly in Android Studio. Of course, you can also use the command line to create a flutter_text_plugin.
flutter create --org com.example --plugin flutter_text_plugin
If you want to support swift or kotlin, you can create it with the following command:
flutter create --org com.example --plugin -i swift -a kotlin flutter_text_plugin
For more parameter options, you can check the help document. Of course, it is recommended to create it directly with AS, which is simple and intuitive. Open the project with AS and you can see the organizational structure of the project.
root
android
example
ios
lib
...
The android and ios folders are where we will write the native layer of the plug-in. The lib folder is where we write the mapping to the native layer. Native and flutter cannot communicate directly and must be called indirectly through MethodChannel. The example folder is an example project, and the written plug-in can be verified directly in this project. In this article, we mainly work in the android directory, which is the android part.
3. Write Android code
Use AS to open the flutter_text_plugin/android project, which is more convenient for development. But after opening it, you will find a lot of errors, prompting that flutter-related things cannot be found. If we look carefully at this project, we will find that it is different from the Android projects we usually build using AS. Many parts are missing, and the directories are also different. . This is because this android project does not need to be able to run directly, so a lot of things are reduced. But for those who are new to it, it may be confusing, such as how to add third-party libraries, how to add proguard rules, etc.