title: Flutter - native_pdf_view - "Looking up a deactivated widget's ancestor is unsafe." when using Navigator.pop
body: <p>I have a very basic Flutter app with a button to show a PDF. Clicking the button navigates to a new &quot;Viewer&quot; page that uses native_pdf_view to load the PDF. That works well. When I navigate backwards (ie, by tapping the &quot;back&quot; button), I get the error message</p>
  <pre><code>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.
  </code></pre>
  <p>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).</p>
  <p>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.</p>
  <p>I would be very grateful for any guidance or hints where to look.</p>
  <p>My main.dart file:</p>
  <pre><code>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 &quot;flutter run&quot;. 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
          // &quot;hot reload&quot; (press &quot;r&quot; in the console where you ran &quot;flutter run&quot;,
          // or simply save your changes to &quot;hot reload&quot; 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 &quot;final&quot;.
  
    final String title;
  
    @override
    State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
  }
  
  class _MyHomePageState extends State&lt;MyHomePage&gt; {
    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(&quot;assets/sample.pdf&quot;);
      List&lt;int&gt; bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      print(&quot;Length of sample.pdf: ${data.lengthInBytes}&quot;);
  
      Directory appDocDir = await getApplicationDocumentsDirectory();
      String path = join(appDocDir.path, &quot;sample.pdf&quot;);
      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: &lt;Widget&gt;[
              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) =&gt; Viewer(1)));
                },
                child: Text('Open PDF From Assets'),
              ),
              ElevatedButton(
                onPressed: () {
                  // Navigate back to first route when tapped.
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) =&gt; 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.
      );
    }
  }
  </code></pre>
  <p>viewer.dart:</p>
  <pre><code>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() =&gt; _ViewerState();
  }
  
  
  class _ViewerState extends State&lt;Viewer&gt; {
    String pdfPath = &quot;&quot;;
  
    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(&quot;Loading PDF from assets...&quot;);
        _pdfController = PdfController(
          document: PdfDocument.openAsset(&quot;assets/sample.pdf&quot;),
          //document: PdfDocument.openFile(pdfPath),
          initialPage: 0,
        );
        //setState(() {
        //  isReady = true;
        //});
  
        //});
  
      } else if (widget.pdfId == 2) {
        print(&quot;Loading PDF from openFile...)&quot;);
        //Load with hard-coded path...
  
  
  
        //Load when finding the path at runtime...
  
        getPdfPath().then((value) {
          print(&quot;Loaded path: ${value['path']}&quot;);
  
          _pdfController = PdfController(
            document: PdfDocument.openFile(value['path']),
            //document: PdfDocument.openFile(pdfPath),
            initialPage: 0,
          );
  
          setState(() {
            isReady = true;
          });
        });
      }
      super.initState();
    }
  
    Future&lt;Map&gt; getPdfPath() async {
      Map res = {};
  
      Directory appDocDir = await getApplicationDocumentsDirectory();
      String path = join(appDocDir.path, &quot;sample.pdf&quot;);
  
      res['path'] = path;
      return res;
    }
  
    Future&lt;Map&gt; getPdfPathFromDatabase() async {
      Map res = {};
      //if (loaded_pdf != null) {
        //res['path'] = await loaded_pdf.path_to_pdf();
      //}
      return res;
    }
  
  
    @override
    void dispose() {
      print(&quot;Disposing pdf controlller..&quot;);
      _pdfController.dispose();
      print(&quot;Calling super.dispose...&quot;);
      super.dispose();
    }
  
    @override
    Widget build(BuildContext context) {
      //if (isReady) {
        return Column(
            children: &lt;Widget&gt;[
              ElevatedButton(
                onPressed: () {
                  // Navigate back to first route when tapped.
                  print(&quot;Going to pop context... ${context}&quot;);
                  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(&quot;Document loaded. ${pages} pages&quot;);
                    },
                    onPageChanged: (page) {
                      currentPage = page;
                    },
                  )
              )
            ]
        );
      //} else {
      //  return Text(&quot;Not Ready Yet...&quot;);
      //}
    }
  }
  </code></pre>