I'm trying to make a api call but I can't success, everything goes fine until the call, and there stop everything and the function finish, what I do wrong?
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");
}
}
CodePudding user response:
You have probably imported the "wrong" http
. Do it like that:
import 'package:http/http.dart' as http;
You dont need to write http!
because http
is a package and is never null and since you are doing http!
I guess you imported something wrong in your code.
EDIT:
Maybe your device can't reach 10.0.2.2
(or that port), you should set a timeout to find it out fast:
http.post(url, body: msg, headers: headers).timeout(
const Duration(seconds: 3),
onTimeout: () {
// request timed out
return http.Response('Error', 408);
},
);
CodePudding user response:
Have you imported http package like this?
import 'package:http/http.dart' as http;
And use case like this
var response = await http.post(url, body: msg, headers: headers);
CodePudding user response:
add .php to login in the url : https://10.0.2.2:7021/api/Auth/login.php if you are working with php or .py for python