gpt4 book ai didi

flutter - 如何使用 Flutter StreamBuilder 重试错误?

转载 作者:IT王子 更新时间:2023-10-29 06:36:01 25 4
gpt4 key购买 nike

我有一个 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 会再次尝试。我该怎么做?

最佳答案

通常,您应该始终将 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,
);
}
// ...
},
);
}
}

关于flutter - 如何使用 Flutter StreamBuilder 重试错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53721030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com