Search code examples
flutterplugins

Flutter: Alternative to Downloads path provider 28


I have a feature in app where user and download some content he generated. The data comes from assets and dart file string. I want it to get downloaded to Android's downloads directory. The plugin downloads_path_provider_28 uses a deprecated api or embedding. I wanted to know about any plugin that can replace it and work well. I already tried flutter_file_downloader, file_saver, external_path. But none works for my case. https://pub.dev/packages/downloads_path_provider_28 works fine but it might not work in future flutter versions thus i want a newer plugin support.

This is the change I made in my code.

import 'dart:io' as io;

// import 'package:downloads_path_provider_28/downloads_path_provider_28.dart';

class KMLGenerator {
  static generateKML(data, filename) async {
    try {
      // final downloadsDirectory = await DownloadsPathProvider.downloadsDirectory;
      // Directory dir = Directory('/storage/emulated/0/Download');
      var path = "/storage/emulated/0/Download/";
      var savePath = io.Directory(path);
      // var savePath = downloadsDirectory?.path;
      final file = io.File("$savePath/$filename.kml");
      await file.writeAsString(data);
      return Future.value(file);
    } catch (e) {
      print(e);
      return Future.error(e);
    }
  }
}

The error I get:

I/flutter ( 9449): FileSystemException: Cannot open file, path = 'Directory: '/storage/emulated/0/Download/'/SO2_Emission.kml' (OS Error: No such file or directory, errno = 2)

The error is the extra '/

One more thing to mention, it works with downloads_path_provider_28 so I am not sure whats the plugin doing differently


Solution

  • I found the solution:

    import 'dart:io';
    class KMLGenerator {
      static generateKML(data, filename) async {
        try {
          Directory dir = Directory('/storage/emulated/0/Download');
          var savePath = dir.path;
          final file = File("$savePath/$filename.kml");
          await file.writeAsString(data);
          return Future.value(file);
        } catch (e) {
          print(e);
          return Future.error(e);
        }
      }
    }
    

    Seems initialising with datatype Directory did the charm. I will still appreciate if anyone can tell how the extra '/ comes in the approach I was doing earlier.