'Flutter - native_pdf_view - "Looking up a deactivated widget's ancestor is unsafe." when using Navigator.pop

I have a very basic Flutter app with a button to show a PDF. Clicking the button navigates to a new "Viewer" page that uses native_pdf_view to load the PDF. That works well. When I navigate backwards (ie, by tapping the "back" button), I get the error message

The following assertion was thrown while finalizing the widget tree:
Looking up a deactivated widget's ancestor is unsafe.

At this point the state of the widget's element tree is no longer stable.

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

I've looked over a number of other questions that had the same issue (mostly dialogs), and as far as I can tell, they don't apply in this case. I don't think I'm referencing any contexts that have disappeared (but I must be somewhere, I suppose).

When I remove the PdfView widget from the Viewer class (and just have a Column widget containing a 'Back' button), then it doesn't show an error. This seems to imply that the error is somehow caused by native_pdf_view, but nobody else using native_pdf_view seems to have this issue, so I'm sure I'm the problem :) I also suspect that the issue may be with needing a Key somewhere, but I'm unsure where that would be, since as far as I know, I don't have lists of objects with the same type that would benefit from a key.

I would be very grateful for any guidance or hints where to look.

My main.dart file:

import 'package:flutter/material.dart';
import 'dart:io';
import 'package:path/path.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'viewer.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'PDF Viewer Test',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  void _copyAssetPDF(BuildContext context) async {
    ByteData data = await rootBundle.load("assets/sample.pdf");
    List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    print("Length of sample.pdf: ${data.lengthInBytes}");

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String path = join(appDocDir.path, "sample.pdf");
    await File(path).writeAsBytes(bytes);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () {
                // Navigate back to first route when tapped.
                _copyAssetPDF(context);
              },
              child: Text('Copy PDF to local storage'),
            ),
            ElevatedButton(
              onPressed: () {
                // Navigate back to first route when tapped.
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (context) => Viewer(1)));
              },
              child: Text('Open PDF From Assets'),
            ),
            ElevatedButton(
              onPressed: () {
                // Navigate back to first route when tapped.
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (context) => Viewer(2)));
              },
              child: Text('Open PDF From File'),
            ),
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

viewer.dart:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';


import 'dart:io';
import 'package:path/path.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

import 'package:native_pdf_view/native_pdf_view.dart';

class Viewer extends StatefulWidget {
  final int pdfId;

  ////const Viewer({Key? key, this.pdfId}) : super(key: key);
  //const Viewer({Key? key}) : super(key: key);
  Viewer(this.pdfId);

  @override
  _ViewerState createState() => _ViewerState();
}


class _ViewerState extends State<Viewer> {
  String pdfPath = "";

  int? pages = 0;
  int currentPage = 0;
  bool isReady = false;

  late final PdfController _pdfController;

  @override
  void initState() {
    //getPdfPathFromDatabase().then((value) {

    //setState(() {
    //  pdfPath = value['path'];
    //});

    if (widget.pdfId == 1) {
      print("Loading PDF from assets...");
      _pdfController = PdfController(
        document: PdfDocument.openAsset("assets/sample.pdf"),
        //document: PdfDocument.openFile(pdfPath),
        initialPage: 0,
      );
      //setState(() {
      //  isReady = true;
      //});

      //});

    } else if (widget.pdfId == 2) {
      print("Loading PDF from openFile...)");
      //Load with hard-coded path...



      //Load when finding the path at runtime...

      getPdfPath().then((value) {
        print("Loaded path: ${value['path']}");

        _pdfController = PdfController(
          document: PdfDocument.openFile(value['path']),
          //document: PdfDocument.openFile(pdfPath),
          initialPage: 0,
        );

        setState(() {
          isReady = true;
        });
      });
    }
    super.initState();
  }

  Future<Map> getPdfPath() async {
    Map res = {};

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String path = join(appDocDir.path, "sample.pdf");

    res['path'] = path;
    return res;
  }

  Future<Map> getPdfPathFromDatabase() async {
    Map res = {};
    //if (loaded_pdf != null) {
      //res['path'] = await loaded_pdf.path_to_pdf();
    //}
    return res;
  }


  @override
  void dispose() {
    print("Disposing pdf controlller..");
    _pdfController.dispose();
    print("Calling super.dispose...");
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //if (isReady) {
      return Column(
          children: <Widget>[
            ElevatedButton(
              onPressed: () {
                // Navigate back to first route when tapped.
                print("Going to pop context... ${context}");
                Navigator.pop(context);
              },
              child: Text('Go back!'),
            ),
            Expanded(
                child: PdfView(
                  documentLoader: Center(child: CircularProgressIndicator()),
                  pageLoader: Center(child: CircularProgressIndicator()),
                  controller: _pdfController,
                  onDocumentLoaded: (document) {
                    pages = document.pagesCount;
                    print("Document loaded. ${pages} pages");
                  },
                  onPageChanged: (page) {
                    currentPage = page;
                  },
                )
            )
          ]
      );
    //} else {
    //  return Text("Not Ready Yet...");
    //}
  }
}


Solution 1:[1]

This was a problem using a pre-release version of Flutter (Flutter 2.9.0-pre). When downgrading to Flutter 2.8 (which is stable), the problem goes away.

It's possible the native_pdf_view widget has not been fully upgraded to work with Flutter 2.9 yet, so the solution for now to solve the problem is to use a stable version of Flutter.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris