【问题标题】:Is it possible to make web only injection with Injectable?是否可以使用 Injectable 进行仅 Web 注入?
【发布时间】:2022-06-13 20:02:54
【问题描述】:

我正在使用Injectable,我有两个课程。 WebImageDownloaderMobileImageDownloader。两者都在实现ImageDownloader,这是一个抽象类。我正在使用 Injectable 将 Web 和移动图像下载器注册为 ImageDownloader,一个 registered under web,一个在 mobile 环境下。

但由于 WebImageDownloader 具有 dart:js 和 dart:html 导入,我无法运行我的代码。因为找不到这些库。

我在一些答案中看到人们在 dart:io 和 dart:html 之间进行条件导入,但它对我不起作用。

另外,这个问题是 Injectable 的问题。

【问题讨论】:

    标签: flutter


    【解决方案1】:
    import 'MobileFileDownloader.dart'
    if (dart.library.html) 'WebFileDownloadService.dart';
    
    abstract class NativeFileDownloader {
      void downloadFile(List<int> bytes, String downloadName);
      factory NativeFileDownloader() =>getDownloader();
    }
    

    import 'NativeFileDownloader.dart';
    
    class WebFileDownloadService implements NativeFileDownloader{
       void downloadFile(List<int> bytes, String downloadName) {
        // Encode our file in base64
        final _base64 = base64Encode(bytes);
        // Create the link with the file
        final anchor = AnchorElement(href: 'data:application/octet-stream;base64,$_base64')
          ..target = 'blank'
          ..setAttribute('download', downloadName);
        // add the name
        //anchor.download = downloadName;
        // trigger download
        document.body?.append(anchor);
        anchor.click();
        anchor.remove();
        return;
      }
    }
    NativeFileDownloader getDownloader()=>WebFileDownloadService();
    

    import 'package:flovo/Services/FileDownloadService/Native/NativeFileDownloader.dart';
    
    class MobileFileDownloader implements NativeFileDownloader{
      @override
      void downloadFile(List<int> bytes, String downloadName) {
      }
    
    }
    
    NativeFileDownloader getDownloader()=>MobileFileDownloader();
    

    使用 => NativeFileDownloader().downloadFile(list, 'image.jpeg');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      相关资源
      最近更新 更多