gpt4 book ai didi

flutter - Flutter/Dart-为什么我的Future返回Null?

转载 作者:行者123 更新时间:2023-12-03 04:13:21 25 4
gpt4 key购买 nike

我想返回从Http Post的response.body中提取的字符串。但是我的代码返回null而不是字符串。如果将字符串oldname放在request.send()的范围内,则可以正常打印,但是在调用uploadAudio方法时需要将其返回。我究竟做错了什么?

Future<String> uploadAudio({String currentuserid, String filepath}) async {

String oldname;
final serverurl = "http://example.com/audiofile.php";

var request = http.MultipartRequest('POST', Uri.parse(serverurl));
request.fields['userid'] = currentuserid;

var multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
contentType: MediaType("audio", "mp4"));
request.files.add(multiPartFile);
request.send().then((result) async {
http.Response.fromStream(result).then((response) {
if (response.statusCode == 200) {
String serverResponse = response.body;
const start = "gxz";
const end = "zxg";
final startIndex = serverResponse.indexOf(start);
final endIndex = serverResponse.indexOf(end, startIndex + start.length);
oldname = serverResponse.substring(startIndex + start.length, endIndex);
}
});
});
print oldname;
return oldname;
}

最佳答案

我认为您的混淆来自您混合使用awaitthen()的事实。我建议您总体上保持一个概念。
我已经重写了您的代码,因此它现在到处都使用await(也将其清理了一下):

Future<String> uploadAudio({String currentuserid, String filepath}) async {
const serverurl = "http://example.com/audiofile.php";

final request = http.MultipartRequest('POST', Uri.parse(serverurl))
..fields['userid'] = currentuserid;

final multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
contentType: MediaType("audio", "mp4"));

request.files.add(multiPartFile);

final response = await http.Response.fromStream(await request.send());
String oldname;

if (response.statusCode == 200) {
final serverResponse = response.body;
const start = "gxz";
const end = "zxg";
final startIndex = serverResponse.indexOf(start);
final endIndex = serverResponse.indexOf(end, startIndex + start.length);
oldname = serverResponse.substring(startIndex + start.length, endIndex);
}

print(oldname);
return oldname;
}
如您所见,现在不需要所有嵌套的 then()方法,现在更容易阅读代码。

关于flutter - Flutter/Dart-为什么我的Future返回Null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63199726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com