簡體   English   中英

Flutter 如何使用 firestore 從 streambuilder 進行分頁(延遲加載)

[英]Flutter How to make a pagination from streambuilder with firestore (lazy loading)

您好,我是顫振移動開發的新手。 我想做一個分頁(從帶有firestore的streambuilder延遲加載)。 事實上,當我做一個流時,所有的文檔都加載了,這需要很長時間,而且我的應用程序有時也會出錯(可能是因為我在內存中加載了很多數據)。 我想通過使用分頁來簡化事情,但我真的不知道該怎么做。 或者您可以每次調用加載 10 個文檔。 請幫助我找到一個解決方案,以避免干擾我的應用程序並減少每次調用加載的文檔。 這是提要部分的完整代碼

class FeedJob extends StatefulWidget {
  FeedJob({Key? key}) : super(key: key);

  @override
  _FeedJobState createState() => _FeedJobState();
}

class _FeedJobState extends State<FeedJob> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: StreamBuilder<QuerySnapshot>(
            stream: FirebaseFirestore.instance
                .collection("job_feed")
                .orderBy("time", descending: true)
                .snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Center(
                  child: CircularProgressIndicator(),
                );
              } else {
                return Column(
                  children: [
                    Expanded(
                        flex: 0,
                        child: Column(children: [
                          TiTle(title: "Feeds"),
                        ])),
                    Expanded(
                      child: ListView(
                        children: [
                          ListView(
                              shrinkWrap: true,
                              physics: NeverScrollableScrollPhysics(),
                              children: snapshot.data!.docs.map((e) {
                                return Column(
                                  children: [
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Card(
                                        child: Column(
                                          children: [
                                            ListTile(
                                              leading: Container(
                                                width: 40,
                                                height: 40,
                                                alignment: Alignment.topCenter,
                                                decoration: BoxDecoration(
                                                    image: DecorationImage(
                                                        alignment:
                                                            Alignment.topCenter,
                                                        fit: BoxFit.cover,
                                                        image:
                                                            CachedNetworkImageProvider(
                                                                e.get(
                                                                    'photo'))),
                                                    color: Colors.blue
                                                        .withOpacity(.2),
                                                    borderRadius:
                                                        BorderRadius.all(
                                                            Radius.circular(
                                                                20))),
                                              ),
                                              trailing: Column(
                                                children: [
                                                  Icon(Icons.comment_rounded,
                                                      size: 15,
                                                      color: Colors.grey),
                                                  Text("comment".tr,
                                                      style: TextStyle(
                                                          fontSize: 8,
                                                          color: Colors.grey))
                                                ],
                                              ),
                                              title: Text(e.get('name'),
                                                  style: TextStyle(
                                                      color: Colors.black,
                                                      fontSize: 10,
                                                      fontWeight:
                                                          FontWeight.bold)),
                                              subtitle:
                                                  Text(e.get('time').toString(),
                                                      style: TextStyle(
                                                        fontSize: 8,
                                                        color: Colors.grey,
                                                      )),
                                            ),
                                            Padding(
                                              padding: const EdgeInsets.only(
                                                  left: 5.0,
                                                  right: 8,
                                                  bottom: 15),
                                              child: Text(
                                                e.get('description'),
                                                textAlign: TextAlign.justify,
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                    )
                                  ],
                                );
                              }).toList()),
                        ],
                      ),
                    ),
                  ],
                );
              }
            }));
  }
}

您可以使用startAfterDocument告訴 Firestore 您獲取的最后一個文檔是什么(假設您每次都保留對它的引用)。

// Prepare the query.
final List<JobModel> fetchedData = [];
final int firstBatchSize = 6;
final int nextBatchSize = 12;

DocumentSnapshot<JobModel>? lastDocument;

final Query<DestinationModel> query = FirebaseFirestore.instance  
  .collection('jobs')
  .orderBy('time', descending: true)
  .withConverter<JobModel>(
    fromFirestore: (snapshot, _) =>  JobModel.fromFirestore(snapshot),
    toFirestore: (JobModel job, _) => job.toFirestore(),
  );

// Set the starting point of the query.
if (lastDocument != null) query.startAfterDocument(lastDocument);

// Set the limit for the query.
query.limit(fetchedData.isEmpty ? firstBatchSize : nextBatchSize);

// Run the query.
final QuerySnapshot<JobModel> results = await query.get();

// Do something with the results; Store the last document fetched.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM