Read now

Flutter with Android Native Code

Flutter is a very beautiful and powerful toolkit for creating an app for mobile, web and desktop with a single codebase. It supports both Android and iOS for mobile applications. But in some scenarios, you could face the requirement to code separately for Android or IOS. So, In this blog, we will learn how we can run the Flutter with Android Native Code.

You can also check the flutter doc for more detailed information.

Suppose you have created a new flutter application. So your main.dart file will look something like the below-provided example.

Now to call the Android native code we would have to use MethodChannel class. Let’s get some info on MethodChannel class.

According to the flutter doc “A named channel for communicating with platform plugins using asynchronous method calls.” So using this class you will be calling a function according to its name and the program will look for its implementation in the Android or the iOS code. How we can do this? Let’s look at some code.

Steps to perform

First, we need to create a MethodChannel. You can do that inside your _MyHomePageState class.

and we will call the “turnOnWifi” function using its name.

As you can see in the above code segment, We have used the “platform” variable and invoked its invokeMethod function with the function name in native code. This will call the native function. Right now, It will give you an exception because if have not declared our turnOnWifi yet in the native code.

After doing all this, Now we will add the Android-specific code in our MainActivity.

For this, You need to open the Android host portion of your Flutter app in Android Studio.

  1. Start Android Studio
  2. Select the menu item File > Open…
  3. Navigate to the directory holding your Flutter app, and select the android folder inside it. Click OK.
  4. Open the file MainActivity.kt located in the kotlin folder in the Project view. (Note: If editing with Android Studio 2.3, note that the kotlin folder is shown as if named java.)

Here, you will have to declare the same channel that you have declared in your flutter part.

then, inside you configureFlutterEngine function below the GeneratedPluginRegistrant.registerWith(flutterEngine) you will have to add a method call handler

Now suppose you have a function that turns the WIFI on.

You can call this function from the setMethodCallHandler and the below code segment will provide you an idea on how to do it.

We have used a when here which will check the call.method and will execute the line of code accordingly.

That’s all for this blog. Thank you very much. This is Vedesh Kumar signing off.

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close