简体   繁体   中英

How to display the data from firebase using FutureBuilder in Flutter

    Future<List<DocumentSnapshot>> getData() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore
    .collection("LiveGames")
    .where("Title", isEqualTo: "Solo")
    .getDocuments();
return qn.documents;

}

I have extracted the data using this function getData() to use it in the FutureBuilder.

  FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Padding(
          padding: const EdgeInsets.only(
            top: 50,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Center(
                child: SpinKitCircle(
                  color: Color.fromRGBO(91, 74, 127, 10),
                  size: 50.0,
                ),
              ),
            ],
          ),
        );
      } else {
        return ListView.builder(
            itemCount: snapshot.data.length,

            itemBuilder: (_, index) {
              return SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.all(10),
                      height: 185,
                      width: double.infinity,
                      child: Stack(
                        children: <Widget>[
                          Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(10),
                                  topRight: Radius.circular(10)),
                              color: Colors.blueGrey.shade800,
                            ),
                            height: 150,
                            width: double.infinity,
                            child: Column(
                              mainAxisAlignment:
                                  MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                SizedBox(
                                  height: 6,
                                ),
                                Expanded(
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceAround,
                                    children: <Widget>[
                                      Column(
                                        children: <Widget>[
                                          SizedBox(
                                            height: 5,
                                          ),
                                          Text("Date",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                          Text(
                                              snapshot.data[index]
                                                  .data["GameDate"],
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                        ],
                                      ),
                                      Column(
                                        children: <Widget>[
                                          SizedBox(
                                            height: 5,
                                          ),
                                          Text("Time",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                          Text(
                                              snapshot.data[index]
                                                  .data["GameTime"],
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                        ],
                                      ),
                                      Column(
                                        children: <Widget>[
                                          SizedBox(
                                            height: 5,
                                          ),
                                          Text("Map",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                          Text(
                                              snapshot.data[index]
                                                  .data["MapName"],
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                        ],
                                      ),
                                      Column(
                                        children: <Widget>[
                                          SizedBox(
                                            height: 5,
                                          ),
                                          Text("Mode",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                          Text(
                                              snapshot.data[index]
                                                  .data["GameMode"],
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                        ],
                                      )
                                    ],
                                  ),
                                ),
                                Divider(
                                  color: Colors.white,
                                ),
                                Expanded(
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceAround,
                                    children: <Widget>[
                                      Column(
                                        children: <Widget>[
                                          SizedBox(
                                            height: 5,
                                          ),
                                          Text("Players Joined",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                          Text(
                                              "${snapshot.data[index].data["RemainingPlayers"]}",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                        ],
                                      ),
                                      Column(
                                        children: <Widget>[
                                          SizedBox(
                                            height: 5,
                                          ),
                                          Text("Winning",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                          Expanded(
                                              child: FlatButton(
                                                  child: Icon(
                                                    Icons.arrow_drop_down,
                                                    size: 18,
                                                    color: Colors.white,
                                                  ),
                                                  onPressed: () {
                                                    showModalBottomSheet(
                                                      backgroundColor:
                                                          Colors.orange
                                                              .shade500,
                                                      shape:
                                                          RoundedRectangleBorder(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .only(
                                                        topLeft:
                                                            Radius.circular(
                                                                15),
                                                        topRight:
                                                            Radius.circular(
                                                                15),
                                                      )),
                                                      context: context,
                                                      builder: (context) {
                                                        return Container(
                                                          child: Column(
                                                            children: <Widget>[

                                                            ],
                                                          ),
                                                        );
                                                      },
                                                    );
                                                  }))
                                        ],
                                      ),
                                      Column(
                                        children: <Widget>[
                                          SizedBox(
                                            height: 5,
                                          ),
                                          Text("Remaining Players",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                          Text(
                                              "${snapshot.data[index].data["TotalSeats"]}",
                                              style: TextStyle(
                                                color: Colors.white,
                                              )),
                                        ],
                                      )
                                    ],
                                  ),
                                ),
                                Divider(
                                  color: Colors.white,
                                ),
                                Expanded(
                                  child: Container(
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceAround,
                                      children: <Widget>[
                                        Column(
                                          children: <Widget>[
                                            Text("Per Kill",
                                                style: TextStyle(
                                                  color: Colors.white,
                                                )),
                                            Text(
                                                "₹ ${snapshot.data[index].data["PerKill"]}",
                                                style: TextStyle(
                                                  color: Colors.white,
                                                )),
                                          ],
                                        ),
                                        Column(
                                          children: <Widget>[
                                            Text("Entry Fees",
                                                style: TextStyle(
                                                  color: Colors.white,
                                                )),
                                            Text(
                                                "₹ ${snapshot.data[index].data["Entryfees"]}",
                                                style: TextStyle(
                                                  color: Colors.white,
                                                )),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 150),
                            height: 35,
                            width: double.infinity,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(10),
                                  bottomRight: Radius.circular(10)),
                              color: Colors.orange,
                            ),
                            child: Padding(
                              padding: const EdgeInsets.only(left: 125),
                              child: InkWell(
                                onTap: () {
                                  print("Solo Joined");
                                },
                                child: Text(
                                  "Join Contest",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 25,
                                    fontFamily: "OpenSans",
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            });
      }
    },
  ),

And then i have displayed some Widgets according to the data. 火力地堡数据 火力地堡数据

But in database i have some rank values and i want to display the data in the bottomsheet if the rank from 2 to 10 and 11 to 20 and 21 to 40 are zeros i do not want to display in the bottom sheet only rank1 player i want it to display but if Rank1 player and all the players from rank 1 to 40 some values are there then i have to display the all the data in the bottomSheet

From your question, I don't see any issues on using FutureBuilder in Flutter. The issue here seems to lean more on how you can manage your Firestore data to be displayed.

If you'd like to filter out Players to be displayed base from their Rank . What you can do here is create a Collections for Players where you can sort them by Rank .

Say you'd only like to display Players with Rank 1 in your List.

FirebaseFirestore.instance
    .collection('players')
    .where('rank', isEqualTo: 1)
    .snapshots()

For Rank with ranges, say Ranks 2-10, compound queries can be utilized. For querying in Flutter, you can check the API reference for its equivalence.

FirebaseFirestore.instance
    .collection('players')
    .where('rank', isGreaterThanOrEqualTo: 2)
    .where('rank', isLessThanOrEqualTo: 10)
    .snapshots()

Here's a sample that I posted previously that filters and displays all carModels base from the selected carMake. It uses StreamBuilder though. I'm curious on your choice for using FutureBuilder instead of StreamBuilder .

Update 2023 with null safety

Try the following example:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: FutureBuilder<QuerySnapshot>(
        future: FirebaseFirestore
                .instance
                .collection('users') // 👈 Your collection name here
                .get(), 
        builder: (_, snapshot) {
          if (snapshot.hasError) return Text('Error = ${snapshot.error}');
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text("Loading");
          }
          return ListView(
              children: snapshot.data!.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
            return ListTile(
              title: Text(data['avatar']), // 👈 Your valid data here
            );
          }).toList());
        },
      )),
    );
  }

Also refer: How to use StreamBuilder and FutureBuilder for single and multiple documents

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