当有SocketException时,我想返回CircularProgressIndicator,但这不起作用,并且由于此异常,需要互联网运行的完整代码无法运行。
我该如何解决?如果有人知道,请提前谢谢:
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: StreamBuilder(
stream: Firestore.instance.collection('images').snapshots(),
builder: (context, snapshot) {
try {
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
for (int i = 0; i < snapshot.data.documents.length; i++) {
listOfUrls.add(snapshot.data.documents[i]['url']);
listOfPics.add(Card(
color: Colors.black12,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Image.network(listOfUrls[i])));
}
return Bar();
} on SocketException catch (_) {
return Center(
child: Text('Connect to the internet'),
);
}
}),
));
}
}
答案 0 :(得分:0)
try..catch
中的任何代码都无法触发SocketException
。您应该尝试使用snapshot.hasError
getter:
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: StreamBuilder(
stream: Firestore.instance.collection('images').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError && snapshot.error is SocketException)
return Center(
child: Text('Connect to the internet'),
);
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
for (int i = 0; i < snapshot.data.documents.length; i++) {
listOfUrls.add(snapshot.data.documents[i]['url']);
listOfPics.add(Card(
color: Colors.black12,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Image.network(listOfUrls[i])));
}
return Bar();
}),
));
}