我正在开发一个下载pdf的图书应用,但在获取完整的下载路径(使用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();
}
}
答案 0 :(得分:0)
这应该有效。当您获得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();
}
}
}