Flutter无法根据User ID获取并显示用户名的问题求助
问题:Flutter调用SpringBoot字符串接口出现FormatException,无法显示用户名
问题描述
正在开发基于Flutter(Android Studio)、SpringBoot(IntelliJ IDEA 2023.3.4)和MySQL Workbench 8.0 CE的项目,需求是通过Profile模块输入的User ID获取用户名。目前服务端终端能正常打印获取到的用户名,但Flutter模拟器无法显示,同时抛出FormatException格式异常。其他数值类型(心率、步数)的接口工作正常,仅字符串类型的用户名接口存在问题。
报错信息
I/flutter ( 9262): Error fetching profile name: FormatException: Unexpected character(at character 1) I/flutter ( 9262): Sophia Brown I/flutter ( 9262): ^
原因分析
- 服务端
getNameById接口直接返回纯字符串(如"Sophia Brown"),但Flutter代码中使用jsonDecode(response.body)['profileName']尝试将响应解析为JSON对象并读取profileName字段。 - JSON解析要求响应必须是标准JSON格式(如
{"profileName":"Sophia Brown"}),纯字符串不符合JSON对象的格式规范,因此抛出FormatException。
解决方案
两种方案任选其一即可:
方案一:修改SpringBoot服务端,返回标准JSON格式
将getNameById接口的返回值改为包含用户名的键值对对象,确保响应为合法JSON。
修改后的EmployeeController.java中getNameById方法:
@GetMapping("/getNameById/{id}") public Map<String, String> getNameById(@PathVariable long id) { Map<String, String> response = new HashMap<>(); EmployeeDetails employeeDetails = employeeRepo.findById(id); if (employeeDetails != null) { System.out.println(employeeDetails.getName()); response.put("profileName", employeeDetails.getName()); return response; } else { response.put("profileName", ""); return response; } }
也可以自定义DTO类封装返回数据,效果一致。
方案二:修改Flutter客户端,直接使用响应体字符串
既然服务端返回的是纯字符串,无需进行JSON解析,直接将响应体赋值给profileName即可。
修改后的profile.dart中fetchProfileName方法:
Future<void> fetchProfileName(String userId) async { final url = Uri.parse('http://192.168.0.194:3030/getNameById/$userId'); final headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-auth-token', }; try { final response = await http.get(url, headers: headers); if (response.statusCode == 200) { setState(() { // 直接使用响应体字符串,trim去除可能的空白字符 profileName = response.body.trim(); }); } else { print('Failed to fetch profile name: ${response.statusCode}'); print('Response body: ${response.body}'); } } catch (error) { print('Error fetching profile name: $error'); } }
内容的提问来源于stack exchange,提问作者DarkSigma
相关产品推荐
相关产品推荐

