FutureBuilder Firestore分页

时间:2019-11-20 05:21:25

标签: flutter dart

我想在FutureBuilder中实现分页,我使用SliverGrid,我想在用户到达最后一行时下载10个项目,每10个项目

最初用户获得10个文档,我希望当用户向下滚动时,他将再获得10个文档,并从最后一个文档开始。

FutureBuilder,在这里,我从Firestore中获取数据,然后使用该数据在SliverGrid中构建项目

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          'title',
          style: TextStyle(
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      drawer: CustomDrawer(),
      body: FutureBuilder<QuerySnapshot>(
        future: database.fetchData(categoryChoosen),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return LoadingMainScreen();
          }

          List<Product> products = List<Product>();

          // add each product to the products list
          snapshot.data.documents.forEach((doc) {
            Product newProduct = Product.fromMap(doc);
            products.add(newProduct);
          });

          return CustomScrollView(
            slivers: <Widget>[
              _buildCategoryList(),
              _buildGridProductList(products),
            ],
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(
          Icons.add_shopping_cart,
          size: 30,
        ),
        onPressed: addProduct,
      ),
    );
  }

此处,按产品类别获取数据

class DatabaseService {
  final Firestore _db = Firestore.instance;

  fetchData(String category) {
    if (category != 'all') {
      return _db
          .collection('products')
          .where('category', isEqualTo: category)
          .orderBy('timestamp', descending: true)
          .limit(10)
          .getDocuments();
    }
    return _db
        .collection('products')
        .orderBy('timestamp', descending: true)
        .limit(10)
        .getDocuments();
  }

}

0 个答案:

没有答案