Flutter Use Case: Write platform specific dart code

Veli Bacık
3 min readMay 1, 2023

--

Hello everyone, and welcome back to my series. Here’s how to write dart-specific code. It helps a lot when you’re writing libraries.

A happy International Workers’ Day to all!

Use Case 🔎

Platform-specific code needs to be written using only Dart. This customer is interested in learning how to use HTML on all platforms at the same time.

Idea 🧩

The code needs to be separated into different files. The files included coding solutions for specific platforms. It is necessary to extend some interface for every coding solution, even if it uses different code. In fact, our solution has started after the interface implementation. Platform-specific layers cannot be viewed in this project. If anyone wants to use them, they can just see the interface. Lastly, the conditional import point is critical because it determines which code works on which platform.

Code ✏️

Actually, I’ll make a basic sample for you, but you can read the Vexana package code for better understanding. In my example, only one method will be used and both HTML and I/O power will be used in the same project.

The project cannot be built on mobile apps if you write HTML code without conditional import, so this usage can save you.

To begin with, there is a need for an interface for the same usage. For this example, I created an interface for the first method as a platform name.

abstract class PlatformShow {
String platformName();
}

The main code is ready for use. It is currently necessary to create platform-specific files for the project. This is my first solution for IO layer as text_show.dart.

This is the HTML layer. The main code will be extended with HTML capabilities as a text_show_web class.

That structure must create an adapter function for global usage, as you can see. When you want to use this method, it will help you. The next step is to implement this structure in where we will use it. It is necessary to import this structure in your file before you can use it. Finally, we can apply our structure solution to the file as shown below.

That’s us all. With this solution, you can use Dart code on every platform. When you need a specific library code, it can be helpful to you.

--

--

Veli Bacık
Veli Bacık

Written by Veli Bacık

We always change the world, so just want it. [OLD]Google Developer Expert Flutter & Dart, Gamer, Work More!

No responses yet