问题描述
在我的 Flutter 项目中,我需要在调用 API 时发生套接字异常时显示一些插图图像。我该怎么做?
提前致谢
解决方法
这取决于您想在小部件树中的哪个位置显示它。一个简单的例子是将一个新屏幕推送到导航堆栈上。您将需要在可能发生异常的函数中使用 BuildContext。
{
artist: { mbid: '','#text': 'Tyler,The Creator' },'@attr': { nowplaying: 'true' },mbid: '',album: { mbid: '','#text': 'CALL ME IF YOU GET LOST' },streamable: '0',url: 'https://www.last.fm/music/Tyler,+The+Creator/_/SWEET+%2F+I+THOUGHT+YOU+WANTED+TO+DANCE+(feat.+Brent+Faiyaz+&+Fana+Hues)',name: 'SWEET / I THOUGHT YOU WANTED TO DANCE (feat. Brent Faiyaz & Fana Hues)',image: [
{
size: 'small','#text': 'https://lastfm.freetls.fastly.net/i/u/34s/8bed6cc4a2f68d3bb2228fbe6654b887.gif'
},{
size: 'medium','#text': 'https://lastfm.freetls.fastly.net/i/u/64s/8bed6cc4a2f68d3bb2228fbe6654b887.gif'
},{
size: 'large','#text': 'https://lastfm.freetls.fastly.net/i/u/174s/8bed6cc4a2f68d3bb2228fbe6654b887.gif'
},{
size: 'extralarge','#text': 'https://lastfm.freetls.fastly.net/i/u/300x300/8bed6cc4a2f68d3bb2228fbe6654b887.gif'
}
]
}
另一个示例是根据布尔值将其添加到您的小部件树中。抛出异常时,您将该 bool 设置为 true。
void someMethod(BuildContext context) {
try {
//some code that might throw an exception
} on Exception catch (_) {
Navigator.pushNamed(context,"Your illustration view");
}
}
在您的小部件树中使用它,如下所示:
void someOtherMethod() {
try {
//some code that might throw an exception
} on Exception catch (_) {
setState(() {
hasThrownError = true;
});
}
}
,
这将有助于解决套接字异常和格式异常。
为 httpresponse 创建模型类
class HTTPResponse<T> {
bool isSuccessful;
T data;
String message;
int responseCode;
HTTPResponse(this.isSuccessful,this.data,{this.message,this.responseCode});
}
然后像这样在 api 响应中使用这个模型
Future<HTTPResponse<List<Post>>> getPosts(
{int limit = 20,int page = 1}) async {
String url =
'https://jsonplaceholder.typicode.com/posts?_limit=$limit&_page=$page';
Uri uri = Uri.parse(url);
try {
var response = await http.get(uri);
if (response.statusCode == 200) {
var body = json.decode(response.body);
List<Post> postsList = [];
body.forEach((e) {
Post post = Post.fromJson(e);
postsList.add(post);
});
return HTTPResponse(
true,postsList,responseCode: response.statusCode,);
} else {
return HTTPResponse(false,null,message: 'Invalid response from server',responseCode: response.statusCode);
}
} on SocketException {
return HTTPResponse(false,[],message: 'Unable to reach the internet');
} on FormatException {
return HTTPResponse(false,message: 'Invalid response from server');
} catch (e) {
return HTTPResponse(false,message: "Something went wrong please try in a minute or two");
}
}