Flutter MethodChannel

Mahan Yarmohammad
2 min readMar 31, 2022

Platform Specific Code

Lets start simple, there are 2 scenarios you can connect to native from Flutter:

  1. you want to call native from Flutter and get answer : MethodChannel
  2. native code would have a listener and trigger a callback that you want to use in Flutter (I will cover this in another blog): EventChannel

In this article we’ll use an example project with 2 functionalities: 1. get phone’s battery percentage on button click and 2. get phone’s pressure sensor value.

MethodChannel

So we want to get battery percentage of the phone, this is the first scenario which we use Method channel to call native code and fetch the data.

The steps are :

  1. Create a MethodChannel instance both in Flutter side and native side

2. Override onMethodCall in your Activity or Application class

The getBatteryLevel() function :

3. Call native method from ‘main.dart’

Note: Future (docs) is a Parameterized type used in Flutter to get asynchronous computation result which will eventually ‘complete’ with the result

At last you can call ‘getBatteryLevel()’ in your ‘onPressed’ of the button.

result of the project
the result of the project

The sample project is in the ‘References’ section

References

Flutter documentation:

Github source code:

--

--

Mahan Yarmohammad

I'm a passionate developer interested in web development, android development, AI, and blockchain.