Flutter MethodChannel

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:

--

--

--

I'm a passionate developer interested in web and android development and AI. (Work toward making the future bright for everyone)

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Beginning

New Year’s Resolution

Nightmare Of a Distributed Monolithic Service As a Micro-service And How EDA Is The Best Approach

A Lesson in Actor Systems Or How I Broke Hootsuite Video Posts for ~12 Hours

Alexa Gear App Download For Android

Monster Battle Updates Vol.1

Best QR code generators online: A Detailed Comparison

Coherence VisualVM Plugin 1.1.0 Released

Summary Information

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mahan Yarmohammad

Mahan Yarmohammad

I'm a passionate developer interested in web and android development and AI. (Work toward making the future bright for everyone)

More from Medium

Flutter EventChannel

flutter even channel

Create Rows & Columns in Flutter using Dart in Android Studio🚀

Flutter Installation — Flutter Basic Programming — Part 2

Flutter environment