我在 Flutter 中使用 HttpClient
从我的 API 获取数据,这是我的函数
我正在尝试从响应函数返回值。
Future<String> SendOTPtoVerify(
{String endpoint, String number, String OTP}) async {
try {
var client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
Map valueMap;
await client.postUrl(Uri.parse(endpoint)).then((HttpClientRequest request) {
String body = '{"mobileNumber": "$number","code": "$OTP"}';
request.contentLength = body.length;
request.headers.contentType =
new ContentType("application", "json", charset: "utf-8");
request.write(body);
return request.close();
}).then((HttpClientResponse response) {
response.transform(utf8.decoder).listen((event) {
valueMap = json.decode(event);
// this print works fine and prints the desired result
print("this is the event $event");
});
// I added this return in order to get the event as variable
return event;
});
} catch (e) {
print('Error: $e');
}
}
函数 SendOTPtoVerify
工作正常,API 向我发送响应,但我只能打印它,我想要的是返回它,以便在其他类中使用它。
这是我在其他课程中的代码,但即使我在使用 FutureBuilder
小部件
PinFieldAutoFill(
codeLength: 6,
onCodeChanged: (val){
if(val.length == 6 ) {
FutureBuilder(
future: SendOTPtoVerify(number: widget.full_number,
endpoint: "https://my_api.servehttp.com:3000/api/codeValidation",
OTP: val),
builder: ( BuildContext context , AsyncSnapshot snapshot){
// this print show nothing when I run the app
print("this is the builder");
// even this container is not returned
return Container(child: Text(snapshot.data),);
},
);
}
},
),
请注意,我必须使用 HttpClient
并且事件打印正确,但我无法返回其值
答案 0 :(得分:0)
试试这个方法:
var headers = {
"Authorization": user.token,
"Content-Type": "multipart/form-data; boundary=<calculated when request is sent>",
};
var request = MultipartRequest('POST', Api.saveData);
request.fields.addAll({
"Model": model.trim(),
"Brand": brand.trim(),
"MAC": version.trim(),
"IMEI": appVersion.trim(),
"PhoneNumber": (user.phone ?? "").trim(),
});
for (var file in files) {
request.files.add(
await MultipartFile.fromPath("ListFiles", file.path),
);
}
request.headers.addAll(Map<String, String>.from(headers));
var response = await request.send();
String result = await response.stream.bytesToString();
return response.statusCode;
这里,result
是您想要的来自 API
的回复。
如果您有任何问题,请随时告诉我。
快乐编码。