Flutter:未处理的异常:无法加载资产

问题描述 投票:0回答:1

我正在尝试构建一个其中一个按钮应该打开pdf的应用程序。我在此链接中使用了指南:https://pspdfkit.com/blog/2019/opening-a-pdf-in-flutter/,但是在应用程序首次运行时它将无法正常运行,只有在热重载/重启后才能运行。我试着拍打干净。 pubspec.yaml的输出也是退出代码0

flutter:
  assets:
    - PDFs/MyDoc.pdf
    - assets/

这里是代码段:

import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'package:path_provider/path_provider.dart';

const String _documentPath = 'PDFs/MyDoc.pdf';

void main() => runApp(MaterialApp(
      home: FadyCard(),
    ));

class FadyCard extends StatefulWidget {
  @override
  _FadyCardState createState() => _FadyCardState();
}

class _FadyCardState extends State<FadyCard> {

  Future<String> prepareTestPdf() async {
    final ByteData bytes =
        await DefaultAssetBundle.of(context).load(_documentPath);
    final Uint8List list = bytes.buffer.asUint8List();

    final tempDir = await getTemporaryDirectory();
    final tempDocumentPath = '${tempDir.path}/$_documentPath';

    final file = await File(tempDocumentPath).create(recursive: true);
    file.writeAsBytesSync(list);
    return tempDocumentPath;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[900],
      appBar: AppBar(
        title: Text('Document'),
        centerTitle: true,
        backgroundColor: Colors.grey[850],
        elevation: 0,
      ),
      bottomNavigationBar: BottomAppBar(
        shape: const CircularNotchedRectangle(),
        child: Container(
          height: 50.0,
        ),
        color: Colors.grey[850],
      ),
      floatingActionButton: FloatingActionButton(
         onPressed: () => {
        prepareTestPdf().then((path) {
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => FullPdfViewerScreen(path)),
          );
        })
      },
        child: Icon(Icons.folder, color: Colors.amber,),
        backgroundColor: Colors.grey[700],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }
}


class FullPdfViewerScreen extends StatelessWidget {
  final String pdfPath;

  FullPdfViewerScreen(this.pdfPath);

  @override
  Widget build(BuildContext context) {
    return PDFViewerScaffold(
        appBar: AppBar(
          title: Text("My Document"),
          backgroundColor: Colors.grey[800],
        ),
        path: pdfPath);
  }
}

提前感谢。

flutter dart load assets
1个回答
0
投票
FadyCard是StateFull窗口小部件,您需要在setState内更新PDF。尝试这样(未测试)

onPressed: () => { setState(() { prepareTestPdf().then((path) { Navigator.push( context, MaterialPageRoute( builder: (context) => FullPdfViewerScreen(path)), ); }) }) }

© www.soinside.com 2019 - 2024. All rights reserved.