我试图做一个api调用,但我不能成功,一切都很好,直到调用,那里停止一切和函数完成,我做错了什么?
Future<String> get() async {
var url = Uri.parse("https://10.0.2.2:7021/api/Auth/login");
var headers = {"content-type": "application/json"};
final msg = jsonEncode(
{"username": "string", "password": "string", "email": "string"});
var response = await http!.post(url, body: msg, headers: headers);
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print("Correct");
return "Correct";
} else {
print(response.statusCode);
print("User not allowed");
throw Exception("User not allowed");
}
}
错误来了
调试窗口您可能导入了"错误的";http
。这样做:
import 'package:http/http.dart' as http;
你不需要写http!
,因为http
是一个包,从来不是空的,因为你正在做http!
,我猜你在你的代码中导入了一些错误的东西。
编辑:
也许你的设备不能到达10.0.2.2
(或那个端口),你应该设置一个超时来快速找到它:
http.post(url, body: msg, headers: headers).timeout(
const Duration(seconds: 3),
onTimeout: () {
// request timed out
return http.Response('Error', 408);
},
);
您是否像这样导入了http包?
import 'package:http/http.dart' as http;
和这样的用例
var response = await http.post(url, body: msg, headers: headers);
在url中添加.phphttps://10.0.2.2:7021/api/Auth/login.php如果您正在使用PHPpython