How to send a screenshot attachment in Mail using Flutter

Thiran Technologies
3 min readAug 4, 2018

--

In enterprise mobile app, reporting the errors on the screen and sending this as an email is a common requirement. There are many way to achieve this and one of it is that, on a button click the app needs to take the screenshot of the current screen and be sent the same as an attachment through email.

Thinking of how this can be done using Flutter, initially thought if this could be implemented using the mailer flutter package. But, this method has its own risk w.r.t handling mail credential and security.

Finally, decided to implement the Flutter Method Channel. The plan is,

  • Build Screenshot functionality in dart
  • Pass the file path through Method Channel to native Android and using Android Intent launch mail app (GMail) and attach the file to it.

The first step is to build screenshot functionality in dart. The RenderRepaintBoundary class would be used to find the widget tree in which the screenshot would be captured. To store the screenshot in a External storage, path_provider package would be used.

In the below snippet, previewContainer is the GlobalKey using which repaintboundary class identifies which widget screenshot is to be taken

Here is the Widget Build(),

Below are the operations on button press to take a screenshot,

  1. RenderRepaintBoundary class creates a separate display list for its child (here Scaffold widget is the child RepaintBoundary).
  2. Display list is converted and formatted as a png Image
  3. Stored in External Storage path as a screenshot.png

Note: App permission to Storage is required to perform the above operations.

As we are done with the Screenshot, as per the requirement the screenshot is required to be sent as an attachment on mail. This could be handled using the Flutter method Channel.

Define method channel

Pass the filepath as a argument using invokeMethod.

Build the mail Intent in MainActivity.java using android native.

Call MethodChannel to get the file path from flutter.

Convert the string file path as Uri and pass it to Intent as EXTRA_STREAM.

As the implementation is done, lets run the flutter to send screenshot an email attachment.

You can get the full source code of this app at the following Github repo.

https://github.com/ThiranTech/screenshot_flutter

Thanks for reading! Please do share this if you like this article.

By sharing more or less, you can signal to us which post really stand out.

--

--