Flutter中Future<String?>始终返回null问题求助
问题分析与解决
1. 核心问题:异步函数未返回有效结果
你的callDalleService声明为Future<String?>类型,但函数内部没有返回异步操作的结果。虽然你在.then()回调里return了值,但这个return仅属于回调函数本身,外层函数没有返回http.post(...).then(...)这个Future对象,导致整个函数默认返回Future.value(null)——这就是为什么哪怕硬编码返回值,最终拿到的还是null。
2. 次要问题:状态赋值逻辑错误
在onTap回调里,setIsFetchingImgs == true是相等比较运算符,不是赋值操作,应该改为setIsFetchingImgs = true(如果是Flutter的状态管理,需要用setState包裹,比如setState(() => isFetchingImgs = true))。
修改后的代码示例
修正后的ApiService类
改用await+try-catch的写法,避免混合await与.then(),同时确保函数返回正确的Future结果:
import 'dart:convert'; import 'package:http/http.dart' as http; class ApiService{ static Future<String?> callDalleService({required String promptText}) async { 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'); try { final response = await http.post( uri, headers: headers, body: jsonBody, encoding: encoding, ); if(response.statusCode == 200) { var jsonResponse = jsonDecode(response.body); print(jsonResponse); return jsonResponse['generatedImgs'].toString(); } else { print('请求错误,状态码:${response.statusCode}'); return null; } } catch(e) { print('请求异常:$e'); return null; } } }
修正后的onTap回调
onTap: () async{ final promptText = _inputTextController.text; print('API call to DALL-E web service with the following prompt $promptText'); // 修正状态赋值(根据你的状态管理方式调整) isFetchingImgs = true; // 如果是Flutter setState: // setState(() { // isFetchingImgs = true; // }); String? finalImage = await ApiService.callDalleService(promptText: promptText); print(finalImage); // 请求结束后更新状态 isFetchingImgs = false; // setState(() { // isFetchingImgs = false; // }); if (finalImage != null) { Navigator.push(context, MaterialPageRoute(builder: (context) => firstOutputPage(finalImage: finalImage))); } else { print('finalImage returned null'); } },
内容的提问来源于stack exchange,提问作者AmoxiciTeo
相关产品推荐
相关产品推荐

