Flutter: Adding native code in Flutter

Grassroot Engineer
3 min readFeb 28, 2021

--

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)

https://flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-kotlin-tab

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).

The table show how Dart values are received on the platform side and vice versa.

Alright do the following basic using the platform channel.

  1. 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
Result after run a standard code.

2. Removed all comment in main.dart by using RegExp

Added RegExp command to remove all comments in the code.
  • 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.

Implement in part of Dart code.

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
Implement in part of Kotlin.

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
Implement in part of Swift.

In summary I will show how related each others between Flutter and Native code.

Overview of 3 files to connect each other.

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.
Result of Android and iOS

My code.

--

--

Grassroot Engineer
Grassroot Engineer

Written by Grassroot Engineer

ATM engineer who is interested in CODING and believe in EFFORT. — https://grassrootengineer.com

No responses yet