我正在开发一个下载pdfs的书籍应用程序,我遇到问题,无法通过pdfviewer获取下载书籍的完整路径。
我有一个函数将路径传递给一个名为path的变量但是当我打印它时它是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;
dynamic path;
var dir;
_PdfScreenState(this.document);
Future<void> getPdf() async{
try{
dir = await getApplicationDocumentsDirectory();
path = "${dir.path}/${document["title"]}.pdf";
} catch(e){
print(e);
}
}
@override
Widget build(BuildContext context) {
getPdf();
print(path); // I need the path here
// the Path I need: //"/data/data/br.com.apps.d.baixa_livros/app_flutter/${document["title"]}.pdf";
return Container();
}
}
这应该工作。当你获得path
时,你需要setState
以便重建小部件。
class _PdfScreenState extends State<PdfScreen> {
final DocumentSnapshot document;
dynamic path;
var dir;
_PdfScreenState(this.document);
@override
void initState() {
super.initState();
getPdf();
}
Future<void> getPdf() async{
try{
dir = await getApplicationDocumentsDirectory();
setState(() {
path = "${dir.path}/${document["title"]}.pdf";
});
} catch(e){
print(e);
}
}
@override
Widget build(BuildContext context) {
if (path == null) {
print("loading"); // show a progress indicator
return CircularProgressIndicator();
} else {
print(path); // I need the path here
return Container();
}
}
}