问题描述
我想在我的应用中使用 ID 删除联系人。当我直接在链接(即静态)中提供 id 而不是 $id
变量时,请求在邮递员上工作正常。当尝试在 Flutter 中使用 HTTP 请求执行此操作时,它会给出 405 响应代码。预期的响应代码是 200。
我是 Flutter 和 RestAPI 的新手,所以我不知道我哪里出错了,我还使用 delectContactModel
构建了一个模型 quicktype.io
。
错误如下:
405
E/Flutter (12820): [ERROR:Flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Exception: Failed to delete contact.
E/Flutter (12820): #0 API_Manager.deleteContact (package:app/services/api_manager.dart:100:7)
E/Flutter (12820): <asynchronous suspension>
API_Manager():
Future<DeleteContactModel> deleteContact(String id) async {
String basicAuth = 'Basic examplebasicauthkey';
final http.Response response = await http.delete(
Uri.parse(
'https://example.com/api/contacts/$id/delete'),headers: <String,String>{
'authorization': basicAuth,'Content-Type': 'application/json; charset=UTF-8',},);
print(response.statusCode);
if (response.statusCode == 200) {
return DeleteContactModel.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to delete contact.');
}
}
查看:
TextEditingController id = TextEditingController();
void initState() {
super.initState();
id.text = widget.contact.id.toString();
}
showAlertDialog(BuildContext context) {
Widget cancelButton = FlatButton(
child: Text("Cancel"),onpressed: () {
Navigator.of(context).pop();
},);
Widget continueButton = FlatButton(
child: Text("Delete"),onpressed: () async {
Navigator.of(context).pop();
await API_Manager().deleteContact(id.text); //Calling the delete function here
},);
AlertDialog alert = AlertDialog(
title: Text(firstName.text + " " + lastName.text),content: Text("Are you sure you want to delete this contact?"),actions: [
cancelButton,continueButton,],);
showDialog(
context: context,builder: (BuildContext context) {
return alert;
},);
}
void handleClick(String value) {
switch (value) {
case 'Edit':
Navigator.push(
context,MaterialPageRoute(builder: (_) => EditContact()));
break;
case 'Delete':
showAlertDialog(context);
break;
}
}
编辑:
如您所见,状态为 200,但这里的问题是我在链接中直接给出了 ID,我不知道如何将其作为变量 id
传递。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)