Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add packages separately for Flutter web and mobile?

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

like image 340
Chinnu Avatar asked Feb 10 '20 12:02

Chinnu


2 Answers

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.

like image 111
lrn Avatar answered Oct 23 '22 16:10

lrn


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;
like image 30
thachnb Avatar answered Oct 23 '22 17:10

thachnb