Flutter: Adding native code in Flutter
In this article I’m going to try to add Native code either Swift (iOS) or Kotlin (Android) in Flutter project and call function from Dart (Flutter) to use in Native code because sometimes we might need to use extended funcitons supported only by the native language.
Android (Kotlin or Java)
iOS (Swift or Objective-C)
In Flutter they have provided platform channels to do this and the architectual is the above you will see that from the Flutter will have MethodChannel to be like a bridge to passed between the client (Flutter app) and host platform (iOS host or Android host).
Before go to do coding we have to know about data types support in each languages (I copied from flutter doc official).
Alright do the following basic using the platform channel.
- Create a project using a standard Flutter command and run in debug mode we will got a sample of counter app like this.
flutter create native_code_in_flutter
2. Removed all comment in main.dart by using RegExp
- Press command + f and click Use Regular Expression.
- Type ‘//.*’
- Press option + enter and delete all comment codes,
then shift + option + F to format code.
Now we will get a clean code in projec.
3. Modify the code by removing the count up function and implement more the function.
4. We will do in part of Android in MainActivity.kt in path below.
If we do in VScode will always show error because this is Kotlin language so I recommend to write Kotlin in Android Studio to avoid showing error to make confusion.
android/app/src/main/kotlin/com/example/native_code_in_flutter
/MainActivity.kt
result.success() = returning value back to Flutter and then Flutter just do await to get value and keep in variable “data” in this line.
final String data = await platform.invokeMethod('getVersion');
5. Then I will do in part of Swift so recommend to do in xCode to avoid error showing during working.
ios/Runner/AppDelegate.swift
In summary I will show how related each others between Flutter and Native code.
The result of this practice will be shown the version of OS in the that phone both Android and iOS by this action.
- one time press = show.
- one time press = unshow.