Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

dart - Flutter - Conditional library import in flutter-web

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/');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...