Home > Enterprise >  Flutter:How to read values of each document and pass it into another file?
Flutter:How to read values of each document and pass it into another file?

Time:12-27

I am trying to create a blog app .How can I create a details page which shows the detailed blog(title,body,date) which has different document field values for each card .

Below is the homepage which displays the blogs .Each card displays title and date of the field.When the user clicks on each card it should navigate to a screen which shows the full blog details including title,body and date .But I don't know how to fetch data for each card each containing different values .

(My document fields in cloud firestore database is title,body,date)

home page

home.dart


        StreamBuilder<QuerySnapshot>(
                stream:
                    FirebaseFirestore.instance.collection('blogs').snapshots(),
                builder: (BuildContext context,
                    AsyncSnapshot<QuerySnapshot> snapshot) {
                  if (!snapshot.hasData) {
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  }
              return Container(
                    child: ListView(
                      children: snapshot.data!.docs.map((document) {
                        return Expanded(
                                  child: InkWell(
                                     child: Card(                                   
                                        child:Column(
                                             children: <Widget>[Text( document['title']),
                                                                Text( document['date']),]
                                                    )
                                               ,),
                                onTap: () {
                                    Navigator.push(context, MaterialPageRoute(
                                      builder: (context) => feeddetails()),
                                );
                       }).toList(),
                           )
                      );

         

CodePudding user response:

the simplest effective way that you can do this is by passing the document data inside the feeddetails call, like this :

 Navigator.push(context, MaterialPageRoute(builder: (context) => feeddetails(documentData: document.data() as Map<String, dynamic>)),

and setting that documentData as a class member in your feeddetails class like this:

 class feeddetails extends StatelessWidget {
   final Map<String, dynamic> documentData;
   feeddetails(super.key, {required this.documentData})

   Widget build(BuildContext context) {
   
    // use the documentData in your widget code
    // ...
  } 
}

now every time the user clicks on a card, a new page will be opened with it's details data.

  • Related