How to import code base on platform in flutter?

Now that flutter support almost all device, you will probabily run into some plugin which support for mobile device but not in web and vice versa.

Same goes for window, linux and you name it. In this post we will see how can we import base on platform in flutter.

Photo by Joshua Aragon on Unsplash

As you already know this is how we import code in normal application.

but what if you have you two plugin one that support mobile devices and one that support web. You can’t run both together since one support for web and while other support for mobile.

That is where import will come into picture. Lets take an example. I have a formio html web page(you can assume dummy webpage) that I want to load it in WebView base on platform.

If you wish to see the code directly, check code snippet directly.

Here is what you have to do to import code base on platform.

  1. First add necessary plugin for both web and mobile.

Note: both 2nd and 3rd file class name should be same.

Now your code should look like below.

In mobileui.dart

In webui.dart

Notice: both webui.dart and mobileui.dart class name is same i.e FormPage

Now In form_detail_page.dart update code to

Notice: import with if condition

we are importing mobileui code but if platform is web than we are importing webui. Only one import will execute at a time.

When we write multiPlatform.FormPage() It will take import base on the condition we have put on top.

That all,Now if you run same application in different device you will get different output base on platform.

Mobile/Web Application Developer