Flutter 分页(12)
介绍
在本文中,我们将使用 Firebase Cloud Firestore 数据库了解 Flutter 中的分页。我们知道,就应用程序性能和带宽成本而言,访问小块数据而不是全部数据是更好的方法,我想包括 Firebase Firestore 根据读取、写入和删除操作的数量向您收费,因此,本文对于希望使用 Firebase Cloud Firestore 数据库作为其应用程序后端的开发人员非常重要。
我们将在下面的示例中实现滚动加载功能以加载更多数据。最初,我们将加载 15 条记录,然后当用户到达列表末尾或列表底部时,我们将加载另外 15 条记录,依此类推。因此,让我们开始使用 Firebase Cloud Firestore 数据库在 Flutter 中进行分页的分步示例教程。
必备条件
- 创建名为“flutter_firebase_pagination”的新项目。
- 我假设您熟悉如何创建 Firebase 项目并在其中初始化 Firestore 数据库。如果您是初学者并且对 Firestore 没有概念,您可以查看我的文章Firebase Firestore CRUD Operation In Flutter。
- 创建 Firebase 数据库后,创建一个名为“products”的集合,并在 products 集合中手动添加 25 个文档。我附上了一张屏幕截图,可以让您轻松了解如何构建我们的收藏。文档中有两个字段——“name”和“short_desc”。
编程步骤
第1步
打开项目中的 pubspec.yaml 文件并将以下依赖项添加到其中。
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
cloud_firestore: ^0.12.7
第2步
打开 main.dart 文件并导入 Firestore 包。
import 'package:cloud_firestore/cloud_firestore.dart';
第 3 步
在状态类中初始化 Firestore 实例。
Firestore firestore = Firestore.instance;
第4步
定义另一个用于存储数据和跟踪加载进度的变量。
List<DocumentSnapshot> products = []; // stores fetched products
bool isLoading = false; // track if products fetching
bool hasMore = true; // flag for more products available or not
int documentLimit = 10; // documents to be fetched per request
DocumentSnapshot lastDocument; // flag for last document from where next 10 records to be fetched
ScrollController _scrollController = ScrollController(); // listener for listview scrolling
第 5 步
定义 getProducts() 函数以获取初始 10 个文档。
getProducts() async {
if (!hasMore) {
print('No More Products');
return;
}
if (isLoading) {
return;
}
setState(() {
isLoading = true;
});
QuerySnapshot querySnapshot;
if (lastDocument == null) {
querySnapshot = await firestore
.collection('products')
.orderBy('name')
.limit(documentLimit)
.getDocuments();
} else {
querySnapshot = await firestore
.collection('products')
.orderBy('name')
.startAfterDocument(lastDocument)
.limit(documentLimit)
.getDocuments();
print(1);
}
if (querySnapshot.documents.length < documentLimit) {
hasMore = false;
}
lastDocument = querySnapshot.documents[querySnapshot.documents.length - 1];
products.addAll(querySnapshot.documents);
setState(() {
isLoading = false;
});
}
第 6 步
定义滚动侦听器。如果用户滚动响应设备高度的 20%,我们将获取更多文档。我们已经在监听器中定义了登录。
_scrollController.addListener(() {
double maxScroll = _scrollController.position.maxScrollExtent;
double currentScroll = _scrollController.position.pixels;
double delta = MediaQuery.of(context).size.height * 0.20;
if (maxScroll - currentScroll <= delta) {
getProducts();
}
});
第 7 步
在构建方法中生成的 UI。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Pagination with Firestore'),
),
body: Column(children: [
Expanded(
child: products.length == 0
? Center(
child: Text('No Data...'),
)
: ListView.builder(
controller: _scrollController,
itemCount: products.length,
itemBuilder: (context, index) {
return ListTile(
contentPadding: EdgeInsets.all(5),
title: Text(products[index].data['name']),
subtitle: Text(products[index].data['short_desc']),
);
},
),
),
isLoading
? Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(5),
color: Colors.yellowAccent,
child: Text(
'Loading',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
)
: Container()
]),
);
}
第 8 步您已使用 Firebase Cloud Firestore 数据库完成 Flutter 分页。对于完整的示例代码,您可以下载 zip 或 pull my repository。
可能的错误
错误:导入 androidx.annotation.NonNull;
解决方案
在 android/gradle.properties 文件中添加以下几行,
结论
在本文中,我们学习了如何使用 Firebase Cloud Firestore 数据库在 Flutter 中实现分页,以及如何提高应用性能并减少带宽使用。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!