Platform Specific Code
Lets start simple, there are 2 scenarios you can connect to native from Flutter:
- you want to call native from Flutter and get answer : MethodChannel
- 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.
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 :
- 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.
The sample project is in the ‘References’ section
Writing custom platform-specific code
This guide describes how to write custom platform-specific code. Some platform-specific functionality is available…
Github source code: