我有一个StreamBuilder对象来呈现FireStore集合中的列表:
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('posts').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
default:
return new ListView(
children:
snapshot.data.documents.map((DocumentSnapshot document) {
return Post(document: document);
}).toList());
}
});
}
我正在尝试使其成为snapshot.hasError
,StreamBuilder再次尝试。我该怎么办?
答案 0 :(得分:5)
通常,您应始终将StreamBuilder
与有状态的小部件结合使用。否则,每次调用build
方法时都会重新创建流。
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Stream<QuerySnapshot> postsStream;
@override
void initState() {
super.initState();
postsStream = Firestore.instance.collection('posts').snapshots();
}
void retryLoad() {
setState(() {
postsStream = Firestore.instance.collection('posts').snapshots();
})
}
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: postsStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return RaisedButton(
child: Text('Retry'),
onPressed: retryLoad,
);
}
// ...
},
);
}
}