flutter-freaccess-hub/lib/shared/widgets/read_view.dart

140 lines
3.5 KiB
Dart

part of 'widgets.dart';
// typedef PDFViewerKey = GlobalKey<SfPdfViewerState>;
abstract interface class Viewer extends StatelessComponent {
final String src;
const Viewer({
super.key,
required this.src,
});
@override
Widget build(BuildContext context) {
return buildViewer(context);
}
Widget buildViewer(BuildContext context);
}
class ReadView extends StatefulWidget {
final String url;
final String title;
const ReadView({
super.key,
required this.url,
required this.title,
});
@override
State<ReadView> createState() => ReadViewState();
}
class ReadViewState extends State<ReadView> {
late PdfController _pdfController;
Future<PdfController> _initializePdf() async {
final file = await downloadPdf(widget.url);
final Future<PdfDocument> document = PdfDocument.openFile(file.path);
return PdfController(document: document);
}
Future<File> downloadPdf(String url) async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final bytes = response.bodyBytes;
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/downloaded.pdf');
await file.writeAsBytes(bytes);
return file;
} else {
throw Exception('Falha ao baixar o PDF');
}
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
_buildPDFViewer(),
buildShareButton(),
],
);
}
Positioned buildShareButton() {
return Positioned(
bottom: 10,
right: 10,
child: IconButton(
icon: Icon(
Icons.share,
color: Colors.black,
),
color: Colors.black,
onPressed: onShare,
),
);
}
void onShare() async {
final Uri uri = Uri.parse(widget.url);
final response = await http.get(uri);
if (response.statusCode == 200) {
final XFile xfile = XFile.fromData(response.bodyBytes,
name: '${widget.title}.pdf', mimeType: 'application/pdf');
await Share.shareXFiles([xfile], text: 'Confira este PDF!');
} else {
log('Erro ao baixar o arquivo: ${response.statusCode}');
}
}
Widget buildLoadingIndicator(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 15),
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
FlutterFlowTheme.of(context).primary,
),
),
),
);
}
Widget _buildPDFViewer() => Padding(
padding: EdgeInsets.all(10),
child: FutureBuilder<PdfController>(
future: _initializePdf(),
builder: (context, snapshot) {
if (!snapshot.hasData) return buildLoadingIndicator(context);
return PdfView(
controller: snapshot.data!,
renderer: (PdfPage page) => page.render(
width: page.width * 2,
height: page.height * 2,
cropRect: Rect.fromLTWH(
10.0, 10.0, page.width * 2, page.height * 2),
forPrint: false,
quality: 100,
removeTempFile: true,
format: PdfPageImageFormat.jpeg,
backgroundColor: '#ffffff',
),
scrollDirection: Axis.vertical,
);
}),
);
// Widget get progressIndicator => LoadingUtil.buildLoadingIndicator(context);
@override
void dispose() {
_pdfController.dispose();
super.dispose();
}
}