Flutter and device specific functionality

Issue

I’m very new to flutter but have been reading through a lot of documentation. I can’t seem to understand this part of it though.

I’m pretty sure React Native wraps some of the device APIs (like vibration for example) in a device-agnostic way so you can access them generically. Additional APIs would need plugins, and you would use conditional statements and files to execute on different platforms.

That’s React Native, on flutter how does this work?

  1. Is everything literally a plugin for this?
  2. And, I can’t find any canonical examples of executing code for android and not for iOS for example.

ty!

Solution

1. Is everything literally a plugin for this?

Yes pretty much. However many of the basic plugins you are talking about are maintained by the flutter team themselves. See this for a list of such packages.

I don’t know the reason they are not included in the main SDK for sure but I would say it’s for easier maintainability.

2. Canonical examples of executing code for android and not for iOS for example.

This question has 2 subcategories:

  • Executing different dart code depending on the current platform
  • Calling native code from dart to access platform specific functionalities.

Executing different dart code depending on the current platform

This is the easiest of the two, simple check the value of Platform.is...:

main() {
  if (Platform.isIOS) {
    runApp(MyCupertinoApp())
  } else {
    runApp(MyAndroidApp())
  }
}

You can use this anywhere, from changing the entire app to the color of a button.

Calling native code from dart to access platform specific functionalities

This uses a mechanism called Platform channels. This is how the packages like camera are build for example (they are open source so you can check their code on github directly).

Platform channel is a bigger topic than I can cover here but you can check this great tutorial by the flutter team or simply search Platform Channel flutter on google.

Answered By – Lulupointu

Leave a Comment