I'm learn searching data by ID with package DIO https://pub.dev/packages/dio, my problem is every time I'm type wrong keyword search, the app suddenly crash with debug message 404 Not Found.
I know data not found because I'm type wrong keyword, but I'm already handle this with this code
Widget _searchKeywordMahasiswa() {
return FutureBuilder<List<Mosque>>(
future: api.getMahasiswaById(_searchText),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Text(snapshot.data[index].id);
},
),
);
} else if (!snapshot.data) { <<<<<< IN THIS LINE
return Center(
child: Icon(
Icons.sentiment_very_dissatisfied,
size: 150.0,
),
);
}
return CircularProgressIndicator();
},
);
// return CircularProgressIndicator();
}
Future<List<Mosque>> getMahasiswaById(String id) async{
try {
var apiRespon = await dio.get('${Urls.BASE_API_URL}/mahasiswa/get/id/$id');
var apiResponJson = apiRespon.data;
print(apiResponJson);
return (apiResponJson['data'] as List).map((p)=>Mosque.fromJson(p)).toList();
}on DioError catch (e) { <<<<< IN THIS LINE
if(e.response.statusCode == 404){
print(e.response.statusCode);
}else{
print(e.message);
print(e.request);
}
}
}
In same case my App crash too if i'm get error 400 Bad Request And i'm already handle this error but not works.
Can you Help Me With This?
Errors that don't occur within Flutter's callbacks can't be caught by the framework, but you can handle them by setting up a error handler on the PlatformDispatcher . All errors caught by Flutter are routed to the FlutterError. onError handler. By default, this calls FlutterError.
DioError describes the error info when request failed.
Dio package comes handy as it provides a powerful HTTP client for Dart and Flutter and it supports Interceptors, Global configuration, FormData, Request Cancellation, File Downloading, Timeout etc. Also less boilerplate leads to cleaner code.
Flutter offers an http package that's nice for performing basic network tasks but is pretty daunting to use when handling some advanced features. By comparison, Dio provides an intuitive API for performing advanced network tasks with ease.
var response = await dio.delete(
url,
data: postData,
options: Options(
followRedirects: false,
validateStatus: (status) {
return status < 500;
},
headers: headers,
),
);
please use the code below bro,
add followRedirects, validateStatus to your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With