简体   繁体   中英

How i can pass QuerySnapshot data from one widget to another widget in flutter?

I want to pass querysnapshot data from one widget to another widget. I'm getting data from firebase and I want the pass that data across the widgets. How to pass data from one screen to another screen?

This is how my code looks like:

class Dashboard extends StatefulWidget {
  @override
  _DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
        stream: Firestore.instance.collection('schedules').snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            snapshotData  = snapshot.data;
            return Container(
                child: Column(
              children: <Widget>[
                Expanded(
                    child: ListView.builder(
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {
                          if (snapshot.data.documents[index]['uid']
                              .contains(userData.uid)) {
                            return GestureDetector(
                              onTap: () {
                                Route route = MaterialPageRoute(
                                    builder: (context) => ViewSchedule(//here i want pass));
                                Navigator.push(context, route);
                              },
                              child: Container(
                                height: 180,
                                width: double.infinity,                            
                              ),
                            );
                          } else {
                            return Container();
                          }
                        })),
              ],
            ));
          } else {
            return Column();
          }
        });
  }
}

In your ViewSchedule class, add a constructor

final QuerySnapshot querySnapshot;

ViewSchedule({@required this.querySnapshot})

And then add the following change in your MaterialPageRoute

MaterialPageRoute(
    builder: (context) => ViewSchedule(querySnapshot:snapshot.data));// pass querySnapshot here

Now, if your ViewSchedule widget is Stateless, you can directly access it with this.querySnapshot in your widget and print it using

print("Printing querysnapshot: ${this.querySnapshot}");

If it is a Stateful widget, then you can access it using widget.querySnapshot in your stateful widget.

print("Printing querysnapshot: ${widget.querySnapshot}");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM