[英]how to add data to streams in flutter dart
这里我使用的是List<DocumentSnapshot>
流,我对我的流不太了解。 我认为我们可以在 Flutter 中使用流进行分页,因为它会随着数据的变化而加载。 我认为一切都按预期进行,直到调试时我调试它显示一个异常说流被调用为空,我不知道哪里出错了,也不知道代码是正确的,但代码用于用户滚动到最后新列表被抓取并添加到流中。 根据我的错误,我已经放置了 init 状态以确保流不为空它也给了我错误
class _Articles extends StatefulWidget {
@override
_ArticlesState createState() {
return new _ArticlesState();
}
}
class _ArticlesState extends State<_Articles> {
final firestore = Firestore.instance;
ScrollController controller;
StreamController<List<DocumentSnapshot>> list;
String s;
@override
void initState() {
controller = ScrollController()..addListener(_listen);
addlist(); // this is to enure the stream should not be null
super.initState();
}
@override
void dispose() {
list.close();
controller.removeListener(_listen);
super.dispose();
}
_listen() { // to check user end of the list or not
if (controller.offset >= controller.position.maxScrollExtent &&
!controller.position.outOfRange) {
listadd(); // if end of the list add to stream
}
}
@override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return Container(
padding: EdgeInsets.only(top: 10, bottom: 10),
color: Colors.grey[100],
child: StreamBuilder<List<DocumentSnapshot>>(
stream: list.stream,
builder: (context, snapshot) {
return //some widget like listview builder with data in snapshot
}),
);
}
void addlist() async{
QuerySnapshot list1= await Firestore.instance.collection('articles').limit(3).orderBy('title').getDocuments();
list.add(list1.documents);
s= list1.documents[2].data['title'];
}
void listadd() async{
QuerySnapshot li= await Firestore.instance.collection('articles').orderBy('title').limit(3).startAt([s]).getDocuments();
list.add(li.documents);
s=li.documents[2].data['title'];
}
}
上面是我的代码不知道如何流式传输这只是一个线索和错误,如果代码本身是错误的,请纠正我任何形式的帮助表示赞赏。
list
似乎没有正确初始化,因为 addlist() 没有作为异步运行,即addlist().whenComplete()
。 下面的代码段符合cloud_firestore 2.2.0
您在这里可以做的只是将 QuerySnapshot 添加为流。
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('articles')
.orderBy('title')
.limit(3)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
return //some widget like listview builder with data in snapshot
},
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.