Search code examples
flutterdartsharesharefile

How can I share voice file(mpeg) which in app files to other app(like whatsapp) in flutter


I tried flutter share 2.0.1 pluggin for share voice file but it did not work(No such file). Could you solve this problem or how can I share voice file to other app? Here is my code and error screenshot.


E/flutter (31567): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(assets/voices/pırt.mpeg (No such file or directory), null, null, null)
E/flutter (31567): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:597:7)
E/flutter (31567): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:158:18)

IconButton(
              icon: Icon(Icons.send),
              color: Colors.black,
              iconSize: 35,
              onPressed: () {
                try{
                  Share.shareFiles(["assets/voices/pırt.mpeg"],text: "Share");
                }
                catch(ex){
                  print(ex);
                }
              },
            ),

Solution

  • As the error states, assets/voices/pırt.mpeg is not a valid path to a file on the OS. That's an asset, packaged into your application. If you want to share assets, you need to make them a file on the device first.

    You'll need to add the path_provider dependency:

    dependencies:
      path_provider: ^2.0.1
    

    Then, make a new File and write the data from the asset to the File:

    //Get directory and make a file object
    final Directory dir = await getTemporaryDirectory();
    final File file = File(dir.path + '/mpeg_data');
    
    //Get data from assets
    ByteData data = await rootBundle.load('assets/voices/pırt.mpeg');
    
    //Write actual data
    await file.writeAsBytes(data.buffer.asUint8List());
    

    This should all go before you share the file. Then when you share the file, use the path of the file object you created:

    //Get directory and make a file object
    final Directory dir = await getTemporaryDirectory();
    final File file = File(dir.path);
    
    //Get data from assets
    ByteData data = await rootBundle.load('assets/voices/pırt.mpeg');
    
    //Write actual data
    await file.writeAsBytes(data.buffer.asUint8List());
    
    try{
      Share.shareFiles([file.path],text: "Share");
    }
    catch(ex){
      print(ex);
    }