[英]Future<String?> always return null
很抱歉打扰你,但我有一个问题让我发疯,我需要一些帮助。 我正在创建一个应用程序,我必须使用 API,实际上 API(我确信它有效,因为在我的网站上使用)必须向我发送图像。 为此,我写了这个 function:
import 'dart:ui' as ui;
import 'dart:convert';
import 'dart:developer';
import 'package:http/http.dart' as http;
class ApiService{
static Future<String?> callDalleService({required String promptText}) async {
var queryStartTime = DateTime.now();
final uri= Uri.parse('https://surfaces-notebook-biographies-paying.trycloudflare.com/dalle');
final headers = {'Bypass-Tunnel-Reminder': "go"};
Map<String, dynamic> body = {'text' : promptText,'num_images' : 1};
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
String? finalImage;
final response = await http.post(
uri,
headers: headers,
body: jsonBody,
encoding: encoding,
).then((res) {
if(res.statusCode == 200) {
var jsonResponse = jsonDecode(res.body);
print(jsonResponse);
return finalImage = jsonDecode(res.body)['generatedImgs'].toString();
}
else
{
print('An Error occured with the response');
return null;
}
});
}
}
然后将参数传递给另一个页面,如下所示:
onTap: () async{
final promptText = _inputTextController.text;
print('API call to DALL-E web service with the following prompt $promptText');
setIsFetchingImgs == true;
String? finalImage = await ApiService.callDalleService(promptText: _inputTextController.text);
print(finalImage);
if (finalImage != null) {
Navigator.push(context, MaterialPageRoute(builder: (context) => new firstOutputPage(finalImage: finalImage),));
}else{
print('finalImage returned null');
}
},
仅出于某种原因,该字符串始终为空。 我试图以这种方式拼出字符串的值:
return finalImage = "Test value";
但它仍然总是回来 null ......请帮助我
不要在async
function 中打扰then
- 只需使用await
。
此代码段按预期工作:
static Future<String?> callDalleService({required String promptText}) async {
final response = await http.post(
Uri.parse(
'https://surfaces-notebook-biographies-paying.trycloudflare.com/dalle',
),
headers: {'bypass-tunnel-reminder': 'go'},
body: json.encode({'text': promptText, 'num_images': 1}),
);
if (response.statusCode != 200) {
return null;
}
return json.decode(response.body)['generatedImgs'][0];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.