Supposing that audioplayers|lib/audio_cache.dart
worked only on Android/iOS, I conditionally exclude the following import from a Dart file:
import "package:audioplayers/audio_cache.dart"
in the following way:
import "dart:math" if (dart.library.io) "package:audioplayers/audio_cache.dart";
where "dart:math" can be any fake_stub Dart file. In short this imports a library only for mobile devices in Flutter. Details here (thanks Alois Deniel!).
What would be the best way to hide platform-specific code in Flutter-Web implementation?
import 'dart:io' show Platform;
bool isMobile() => Platform.isAndroid || Platform.isIOS;
class _MyPageState extends State<MyPage> {
dynamic _audioPlayer;
@override
void initState() {
if (isMobile()) {
_audioPlayer = AudioCache(prefix: 'sounds/');
_audioPlayer.load('mysound.mp3');
}
}
}
This naive try fails on AudioCache
reference of course.
Error: Method not found: 'AudioCache'.
_audioPlayer = AudioCache(prefix: 'sounds/');
In this stack overflow question which has similar requirements as yours, I wrote an answer based on this implementation from http package.
I think you can also use a similar approach to handle this conditional dependencies. I have provided a working example there. I am quoting the answer here.
The core idea is as follows.
- Create an abstract class to define the methods you will need to use in genral.
- Create implementations specific to
web
andandroid
dependencies which extends this abstract class.- Create a stub which exposes a method to return the instance of this abstract implementation. This is only to keep the dart analysis tool happy.
- In the abstract class import this stub file along with the conditional imports specific for
mobile
andweb
. Then in its factory constructor return the instance of the specific implementation. This will be handled automatically by conditional import if written correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With