How to use Native code in Flutter
Hello FlutterDevs,
In this article we will learn, How we can use Native code in our Flutter Project for Android and i will also provide you code ??.
For iOS we will discuss in our next article.
Let's Begin ??
We are going to create one Screen/UI. Which have Refresh Button, When we click on Refresh Button, We get Random number , We will generate random number using Native Code (Java or Kotlin) !
Copy this code and call HomePage in main.dart file.
lass HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int randomeNumber = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Android Native Code")),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Random Number: $randomeNumber",
style: const TextStyle(
color: Colors.black,
fontSize: 30,
fontWeight: FontWeight.bold)),
ElevatedButton(
onPressed: (){},
child: const Text("Referesh"),
)
],
),
),
);
}
}
Now, Create MethodChannel in our HomePage, MethodChannel takes one parameter name, We can give it any name, Here i give it NativeChannel.
// Create by passing channel name!
final channel = const MethodChannel('NativeChannel');
Now, open android folder in AndroidStudio.
Then, open MainActivity file, We will write all native code in this MainActivity file for android.
领英推è
Copy paste below code in MainActivity file, Remember my package name is different, So you have to write your package name. You can get package name in app level build.gradle file.
In MainActivity Class We have getRandomNumber function which return random number.
Then we create variable CHANNEL and given it same String as we give to MethodChannel.
Now create setMehodCallHandler. It gives call, result. We will invoke or execute this getRandomNumber function by passing "generateRandomNumber" String from Flutter, and we give result to Dart by calling result.success(mapOf("RandomNumber" to number)).
mapOf("RandomNumber" to number) is nothing. It is simply a Map
/// Replace with your package name
package com.example.bloc_article
import androidx.annotation.NonNul
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.util.*
class MainActivity: FlutterActivity() {
private val CHANNEL = "NativeChannel"
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
if(call.method=="generateRandomNumber"){
val number = getRandomNumber();
result.success(mapOf("RandomNumber" to number));
}
// This method is invoked on the main thread.
// TODO
}
}
/// We call this function and It will get us Random Number!
private fun getRandomNumber(): Int {
return Random().nextInt(200); // create instance of Random class
}
}l
I know you have one Big Question ???
How we can call this Native code in our Flutter? Don't worry guys it is a very easy part.
We can call native code by calling! InvokeMethod it takes String, call this method on Refresh Button and save result in a Map because we we are returning a Map from result.success, then call Setstate for rebuilding a widget tree.
onPressed: () async {
Map data = await channel.invokeMethod("generateRandomNumber");
debugPrint(data.toString());
setState(() {
randomeNumber = data["RandomNumber"];
});
},
We did it guys, If you have any doubt you can reach out me Bhushan Jadhav . You can connect with me on my LinkedIn.
FULL CODE
class _HomePageState extends State<HomePage>
int randomeNumber = 0;
// Create by passing channel name!
final channel = const MethodChannel('NativeChannel');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Android Native Code")),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Random Number: $randomeNumber",
style: const TextStyle(color: Colors.red, fontSize: 30)),
ElevatedButton(
onPressed: () async {
Map data = await channel.invokeMethod("generateRandomNumber");
debugPrint(data.toString());
setState(() {
randomeNumber = data["RandomNumber"];
});
},
child: const Text("Referesh"),
)
],
),
),
);
}
}
Thanks for reading my article and Don't forget to like and share it.