我尝试在Flutter
中使用FutureBuilder
小部件从网络获取一些数据。为此,我使用以下代码:
Future<List<Product>> getWishList() async {
http.Response response = await http.post(
MY_URL,
headers: {
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8'
},
);
if (response.statusCode == 200) {
List<Product> ret = List();
Map<String, dynamic> result;
try {
result = json.decode(response.body);
for (var i = 0; i < result['data'].length; i++) {
ret.add(Product.fromJson(result['data'][i]));
}
return ret;
} catch (e) {
return throw Exception("Json parse error");
}
} else {
return throw Exception("network connection failed");
}
}
AND:
FutureBuilder(
future: getWishList(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.connectionState == ConnectionState.done){
if(snapshot.hasError){
controller.forward(from: 0.0);
return Material(
child: Container(
margin: const EdgeInsets.only(top: 36.0),
width: double.infinity,
child: FadeTransition(
opacity: animation,
child: PButton(
onPressed: (){
setState(() {
getWishList();
});
},
child: Column(
children: <Widget>[
Icon(Icons.perm_scan_wifi,color: Colors.black,size: 76.0,),
SizedBox(height:24.0),
Text("Try again",style: TextStyle(fontSize: 16.0,color: const Color(0XFF222222)),),
],
),
),
),
),
);
}else{
return new ListView(
children: <Widget>[
GestureDetector(
onTap:(){
setState(() {
getWishList();
});
},
child: new Text("Every thing ok"))
]);
}
}else{
return Center(
child: Container(
margin: const EdgeInsets.only(top: 36.0),
child: CircularProgressIndicator()),
);
}
})
现在,如果 HTTP 响应在第一次返回错误,一切都好,但是点击“重试”按钮并且再次出现错误时,控制台会显示以下信息:
[VERBOSE-2:shell.cc(184)] Dart 错误:未处理的异常:Exception: 网络连接失败 _WishListState.getWishList (package:parchino/screen/screen_wish_list.dart:127:14) _WishListState.build... (package:parchino/screen/screen_wish_list.dart:65:33) State.setState (package:flutter/src/widgets/framework.dart:1130:30) _WishListState.build.. (package:parchino/screen/screen_wish_list.dart:64:31) GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24) TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9) TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7) PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9) PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart<…>