Флаттер: необработанное исключение: невозможно загрузить актив - PullRequest
2 голосов
/ 18 января 2020

Я пытаюсь создать приложение, в котором одна из кнопок должна открывать PDF. Я использовал руководство по этой ссылке: https://pspdfkit.com/blog/2019/opening-a-pdf-in-flutter/, однако оно не будет работать при первом запуске приложения, оно работает только после горячей перезагрузки / перезапуска. Я попытался очистить трепетание. Также выводом pubspe c .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);
  }
}

Заранее спасибо.

1 Ответ

0 голосов
/ 21 января 2020

FadyCard - это виджет StateFull, который необходимо обновить в PDF внутри setState. Попробуйте вот так (не проверено)

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