5
votes

I am creating a Flutter project targeting of Android/iOS and Web is there any way to add the supported packages separately for both the Flutter Mobile and Web. For example, I am using the dart:io package in Flutter mobile applications to save the files, but it is not supported in Flutter web, so for web, I am using the dart:js package to download the files in the web application.

For C# we are simply using conditional symbols but Flutter I could not found any solution.

The problem is I could not import both the packages in my main.dart file. Can anyone help me to achieve this

2
You can use a condition with the variable kIsWeb and then use the right package. Otherwise you can split file to build platform specific code in two files and keep the reusable code in the current file.huextrat
You can check this post where it is explained with an example. This aligns with what @Irn has answered below.Abhilash Chandran

2 Answers

6
votes

Dart has conditional imports that can be conditioned on the availability of platform libraries.

That means that you can create one library in your package which uses dart:io, and another which uses dart:js, and then import whichever of these is supported.

import "file_loader.dart" // Version which just throws UnsupportedError
  if (dart.library.io) "file_loader_io.dart"
  if (dart.library.js) "file_loader_js.dart";

// Use imported API.

The important part is that you give these libraries the same API - the same types with the same members, and the same top-level function - so that no matter which library is imported, the code that uses it is still valid.

When you compile the program, only one of the libraries will be used, so you won't get warnings if the other libraries are incorrect. You should test the code on all the supported platforms, just to be sure.

5
votes

You should implement code separately, for example, my_ui_web.dart and my_ui_mobile.dart

Then you can import those files using if:

import 'package:my_awesome_app/my_ui_mobile.dart' 
    if (dart.library.html) 'package:my_awesome_app/my_ui_web.dart' 
    as myUI;