Flutter权限分配按钮触发FormatException错误求助
Flutter权限分配按钮点击后JSON解析错误排查
错误信息
I/flutter ( 6171): Error: FormatException: Unexpected character (at character 1)
I/flutter ( 6171): SyntaxError: Unexpected token n in JSON at position 0
I/flutter ( 6171):
核心问题分析
这个错误说明你在尝试解析非JSON格式的字符串为JSON对象。服务器返回的是错误文本(比如SyntaxError: Unexpected token n...)而非预期的JSON结构,导致json.decode抛出异常。
具体代码问题及修复方案
1. 控制器中rol变量未初始化,传递空值给接口
在AdministratorRolesAssignController的assignRol方法中,rol变量从未被实例化,始终为null。使用rol?.idUser = idUser的空安全赋值不会改变rol的null状态,最终传给接口的参数是null,服务器因此返回错误文本。
修复代码:
void assignRol() async { // 初始化Rol实例,只传入接口需要的字段 Rol assignRol = Rol( idUser: idUser, idRol: idRol, ); await _rolesProvider.assignRol(assignRol); }
2. RolesProvider未处理服务器非成功响应
RolesProvider的assignRol方法中,无论服务器返回什么状态码,都直接尝试解析响应体为JSON。如果服务器因参数错误返回非JSON格式的错误信息,就会触发FormatException。
修复代码:
Future<ResponseApi> assignRol(Rol rol) async { try { Uri url = Uri.http(_url, '$_api/assign'); String bodyParams = json.encode(rol); Map<String, String> headers = { 'Content-type': 'application/json', 'Authorization': sessionUser.sessionToken }; final res = await http.post(url, headers: headers, body: bodyParams); // 仅在成功状态码下解析JSON if (res.statusCode >= 200 && res.statusCode < 300) { final data = json.decode(res.body); return ResponseApi.fromJson(data); } else { print('服务器错误响应内容:${res.body}'); return ResponseApi(success: false, message: '服务器返回错误'); } } catch(e) { print('请求或解析错误:$e'); // 捕获解析异常时,打印原始响应内容方便排查 if (e is FormatException && res != null) { print('无法解析的响应体:${res.body}'); } return ResponseApi(success: false, message: '请求失败'); } }
3. Rol模型的toJson方法存在序列化问题
Rol类的toJson方法中,roles: roles直接传递Listjson.encode无法自动将Rol实例转为JSON结构,会导致序列化失败,服务器可能返回错误。
修复代码:
Map<String, dynamic> toJson() => { "id": id, "name": name, "route": route, "id_user": idUser, "id_rol": idRol, "roles": roles?.map((rol) => rol.toJson())?.toList() ?? [], };
额外排查建议
- 用Postman或curl手动调用
/api/roles/assign接口,传递合法的id_user和id_rol参数,确认服务器返回的是否为合法JSON。 - 检查服务器端代码,确保无论请求成功或失败,都返回JSON格式的响应。
内容的提问来源于stack exchange,提问作者Marcelo_uy
相关产品推荐
相关产品推荐

