Yes, you can use packages for both mobile and web in Flutter. However, not all packages will work seamlessly across both platforms due to the underlying differences in the platforms themselves12.
For example, you might be using the dart:io package in Flutter mobile applications to save files, but it is not supported in Flutter web. So for web, you might use the dart:js package to download files in the web application1.
You can use conditional imports to handle this. 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 supported1.
Here’s an example of how you can do this:
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';
In this example, file_loader.dart is a default file that throws an UnsupportedError. If the dart:io library is available (which means the code is running on a mobile platform), then file_loader_io.dart is imported. If the dart:js library is available (which means the code is running on a web platform), then file_loader_js.dart is imported1.
Remember to 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 valid1.
You should test the code on all the supported platforms, just to be sure1.

Comments
Post a Comment