【发布时间】:2021-04-16 18:07:16
【问题描述】:
我在 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 并且事件打印正确,但我无法返回其值
【问题讨论】:
标签: flutter https flutter-futurebuilder