joseph-grabinger / flutter_to_pdf

Create PDFs but work with normal Flutter Widgets.
MIT License
21 stars 17 forks source link

How do I export a unbuilded widget? #74

Closed xpwmaosldk closed 4 months ago

xpwmaosldk commented 5 months ago
var frame = ExportFrame(
  frameId: 'someFrameId',
  exportDelegate: exportDelegate,
  child: RawImage(
    image: uiImage,
  ), // the widget you want to export
);

frame.build(context);

await exportDelegate.exportToPdfPage('someFrameId');

I tried the approach above, but the frame.build(context); part seems odd.

How can I export the frame without building it?

joseph-grabinger commented 5 months ago

To export an unbuilt widget, one would have to call _exportWidget directly. This is the case since the 'ExportFrame's are registered as soon as they are built. Since the widget is not built yet no frame will be found. Calling _exportWidget directly would bypass all the logic of registering and getting the corresponding frame.

To be able to call the _exportWidget method (https://github.com/joseph-grabinger/flutter_to_pdf/blob/main/lib/export_delegate.dart#L94) it must not be private, so it could be called from outside the ExportDelegate.

This is how you then could call exportWidget :

Widget widget = SomeWidget();
final pw.Widget pdfWidget = await exportDelegate.exportWidget(widget, null);

// Add the pdfWidget to a document.
final pw.Document pdfDoc = pw.Document();
pdfDoc.addPage(pw.Page(
      build: (pw.Context context) => pdfWidget,
));

If this is what you're looking for, feel free to open a PR that implements this functionality so unbuilt widgets could be exported. Within the PR you could then test the functionality to ensure everything works as expected, as this explanation is only theoretical and not tested.

Note: Looking back it, would also be possible to just implement a non-private wrapper function for the _exportWidget method. Maybe something like:

Future<pw.Widget> exportUnbuiltWidget(Widget widget) async => await _exportWidget(widget, null);