Passing List index Data to a Stateful Widget to load PDF document dynamically

402 Views Asked by At

I am trying to pass the 'index' of a List to a Stateful Widget. But it is not working as the 'index' is not being recognized.

From where I am passing data:

onTap: () {
  Navigator.push(context,
    MaterialPageRoute(builder: (context) => DetailsPage(index)));
},

Where the data is being passed:

    class DetailsPage extends StatefulWidget {
       final int index;
       DetailsPage(this.index);
    
      @override
      _MyDetailsPage createState() => _MyDetailsPage();
    }
    
    class _MyDetailsPage extends State<DetailsPage> {
      bool _isLoading = true;
      PDFDocument document;
    
      @override
      void initState() {
        super.initState();
        loadDocument();
      }
    
      List locations = [
        Books(
            name: 'book name 1',
            Booklink:
            'https://storage.googleapis.com/school_books/Class9/ban/Bangla%20Sahitto.pdf'),
        Books(
            name: 'book name 2',
            Booklink:
            'https://storage.googleapis.com/school_books/Class9/ban/Bangla%20Sahitto.pdf')
      ];
    
      loadDocument() async {
        document = await PDFDocument.fromURL(locations[index].Booklink);
        setState(() => _isLoading = false);
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(),
            body: Center(
              child: _isLoading
                  ? Center(child: CircularProgressIndicator())
                  : PDFViewer(
                      document: document,
                      zoomSteps: 1,
                    ),
            ),
          ),
        );
      }
    }

Any idea what I am doing wrong here?

1

There are 1 best solutions below

0
Mohammad Mirshahbazi On BEST ANSWER

Because you pass the data from another page to use that object or variable you need to use widget then call your object or variable like this :

locations[widget.index]