Saving flutter camera image for share

Viewed 887

I am trying to share an image taken from the flutter camera with other users.

The issue is that when I try to share my image, I get an error that the image doesn't exist, making me think that the temporary directory it stores it in no longer exists once the next screen comes. My question is, can I save it to some other location on the phone so it still exists? I am using android. Here is the error I am getting:

 Unhandled Exception: FileSystemException: Cannot create file, path = '/data/user/0/com.example.pictureapp/cache//data/user/0/com.example.pictureapp/cache/2020-03-20 20:10:24.403289.png' (OS Error: No such file or directory, errno = 2)

I have the following code:

onPressed: () async {
          // Take the Picture in a try / catch block. If anything goes wrong,
          // catch the error.
          try {
            // Ensure that the camera is initialized.
            await _initializeControllerFuture;

            /////////////////////////////////////////////////////////
            //below is the code I believe needs to be changed
            ////////////////////////////////////////////////////////
            final path = join(
              // Store the picture in the temp directory.
              // Find the temp directory using the `path_provider` plugin.
              (await getTemporaryDirectory()).path,
              '${DateTime.now()}.png',
            );

            // Attempt to take a picture and log where it's been saved.
            await _controller.takePicture(path);

            // If the picture was taken, display it on a new screen.
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => DisplayPictureScreen(imagePath: path),
              ),
            );
          } catch (e) {
            // If an error occurs, log the error to the console.
            print(e);
          }
        },
      ),
    );
  }
}

// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;

  Future<ByteData> getBytesFromFile() async {
  Uint8List bytes = File(imagePath).readAsBytesSync() as Uint8List;
  return ByteData.view(bytes.buffer);
}

  const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Display the Picture')),
      // The image is stored as a file on the device. Use the `Image.file`
      // constructor with the given path to display the image.
      body: Image.file(File(imagePath)),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          /*
            print("in print");
            Share.share(imagePath);
*/


          getBytesFromFile().then((bytes) {
    Share.file('Share via:', imagePath,
        bytes.buffer.asUint8List(), 'image/png');
  });
        }
      )
    );
  }
}
2 Answers

Here is the code to take picture from camera. Use this onPressed Method.

    final Directory extDir =
                await getTemporaryDirectory(); //or you can use getApplicationDocumentsDirectory();
            final String dirPath = '${extDir.path}/appName/Camera/Images';

    //I think you are missing below line of code.
            await new Directory(dirPath).create(recursive: true);
            final String filePath = '$dirPath/${timestamp()}.jpg';

            if (_controller.value.isTakingPicture) {
              // A capture is already pending, do nothing.
              //return null;
            }

            try {
              await _controller.takePicture(filePath);
              Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => DisplayPictureScreen(imagePath:filePath),
              ),
            );
            } on CameraException catch (e) {
              showException(e);

            }

timestamp method

String timestamp() => new DateTime.now().millisecondsSinceEpoch.toString();

/data/user/0/com.example.pictureapp/cache//data/user/0/com.example.pictureapp/cache/2020-03-20 20:10:24.403289.png looks as if you append the temp dir path twice. It's not clear from the published code where this duplication happens, but step by step, it should be easy to nail it.

Related