0
I am developing in a book app and am stuck on the screen where will open the file . pdf.
I need to get the path of the mobile directory using path_provider to send to pdfviewer but I can’t get the path in the variable outside the method. However if I give hot realod the path is obtained, but when I return to the screen select book, low, and try to open the path becomes null.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_pdf_viewer/flutter_pdf_viewer.dart';
class PdfScreen extends StatefulWidget {
final DocumentSnapshot document;
PdfScreen(this.document);
@override
_PdfScreenState createState() => _PdfScreenState(document);
}
class _PdfScreenState extends State<PdfScreen> {
final DocumentSnapshot document;
_PdfScreenState(this.document);
dynamic path;
Future<dynamic> loadPdf() async{
try{
var dir = await getApplicationDocumentsDirectory();
setState(() {
path = "${dir.path}/${document["title"]}.pdf";
}
return **path**;
}catch(e){
print("ERRO: $e");
return e;
}
}
@override
Widget build(BuildContext context) {
loadPdf();
// path = "/data/data/br.com.apps.d.baixa_livros/app_flutter/${document["title"]}.pdf";
print(path); // **Aqui printa null**
return Container();
}
}
Could not add async, build error because it would need to be Future type.
– djalmafreestyler
@djalmafreestyler My fault, corrected the 1st Output, missed only by a
Future<void>
. Disregard the 2nd Exit, it’s not very elaborate, is that I was without the Flutter to test.– Matheus Ribeiro
I used how you guided, actually had already tested so, on the console prints first a null and then prints several times the path, with setState inside or outside the Try catch.
– djalmafreestyler
@djalmafreestyler As I explained below the first example, the
setState()
causes theWidget
be reconstructed, as soon as its variable is being printed in thebuild()
she will be exhibited whenever herwidget
is rebuilt... You can get around this by using some Patterns like Bloc, but it’s something more advanced.– Matheus Ribeiro
Solved, I needed to use the getPdf method in iniState. Thanks anyway Matheus.
– djalmafreestyler
@Matheusribeiro, is the scratched part still relevant? Wouldn’t it be the case to remove it and leave the answer cleaner? Anything, you can still check the history, but I believe the intention is to
<strike>
was to show the irrelevance of that part of the answer– Jefferson Quesado
@Jeffersonquesado that’s right, I left the 2nd EXIT taxed as a way of saying that it is not the best way to be used. I will make adjustments to make the answer better organized.
– Matheus Ribeiro