14
votes

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/');
1
I know this is not the core of the question, just an example, but I just updated the AudioCache class from the audioplayers package to fully support web :)Luan Nico

1 Answers

8
votes

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.

  1. Create an abstract class to define the methods you will need to use in genral.
  2. Create implementations specific to web and android dependencies which extends this abstract class.
  3. 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.
  4. In the abstract class import this stub file along with the conditional imports specific for mobile and web. Then in its factory constructor return the instance of the specific implementation. This will be handled automatically by conditional import if written correctly.