How to add conditional imports across Flutter mobile,web and window?

3,165

Solution 1

Since there is no conditional import support for window since it comes under dart io. I have this workaround and found it working.
I end up creating file for each platform with different package import.

import 'package:flutter/foundation.dart' show kIsWeb;
import 'dart:io' as io;
if(kIsWeb){
{
     return WebPage();  //your web page with web package import in it
}
else if (!kIsWeb && io.Platform.isWindows) {
     return WindowsPage(); //your window page with window package import in it
    } 
else if(!kIsWeb && io.Platform.isAndroid) {
     return AndroidPage();  //your android page with android package import in it
    } 
//you can add others condition...

Solution 2

For anyone else finding this, note that the accepted answer is not an answer to the question that was asked. The answer to the question that was asked is that you cannot. There is no way to use conditional imports to get different behavior between mobile and desktop; see this comment from the Dart team.

Share:
3,165
KonTash
Author by

KonTash

Updated on December 01, 2022

Comments

  • KonTash
    KonTash over 1 year

    I have flutter application which uses different webview plugin for each platform(mobile, web, window).
    Though I am able to import platform base on web and mobile, I am not able to import for windows.

    I have tried adding else condition if it is not mobile or web, but it is taking mobile plugin.

    1. This is how I import package for web and mobile (Working).
    import 'package:eam_flutter/form/mobileui.dart'
        if (dart.library.html) 'package:eam_flutter/form/webui.dart'
        as multiPlatform;   
    
    1. This is how I import package for web, mobile and windows (Not Working, it is showing mobile webview exception since it doesn't support desktop).
    import 'package:eam_flutter/form/windowui.dart'
        if (dart.library.html) 'package:eam_flutter/form/webui.dart'
        if (dart.library.io) 'package:eam_flutter/form/mobileui.dart'
        as multiPlatform;
    

    How can I specify conditional imports for windows?