Flutter注册功能报错:Text widget需传入非空String
问题解决:Flutter注册功能的非空字符串错误
核心错误点
你的代码里存在两个关键问题导致报错:
HTTP响应属性大小写错误
http.Response的内容属性是小写的body,你代码里写成了大写的Body。response.Body是未定义属性,会返回null,这会引发连锁问题:response.Body != ""的判断永远为false,直接进入错误分支- 若尝试解析
response.Body,会传入null触发空值异常,进而导致Text widget的非空校验失败
错误分支的Text widget未正确使用
错误分支里仅创建了Text("Error Occurred")但未将其渲染到界面,这行代码完全无效。如果需要展示错误提示,得用弹窗、Snackbar等方式实现。
修正后的createUserAccount函数
Future createUserAccount(BuildContext context) async { // show loader here http.Response response = await authService.signUpUser( name: name, email: email, password: password, confirmPassword: confirmPassword, ); if (response.statusCode == 200 && response.body.isNotEmpty) { Map<String, dynamic> res = json.decode(response.body); if (res["status"] == true) { var user = User.fromJson(res["data"]); UserPreferences().setUser(user); Get.offAll(() => GoHome()); return; } else { print(res['message']); // 添加错误提示 Get.snackbar("提示", res['message'] ?? "注册失败"); return; } } else { // 展示错误提示 Get.snackbar("错误", "发生异常,请稍后重试"); return; } }
额外优化建议
- 将
signUpUser函数的参数改为必填非空类型,避免潜在空值风险:
Future<http.Response> signUpUser({ required String name, required String email, required String password, required String confirmPassword, }) async { // 原代码逻辑不变 }
内容的提问来源于stack exchange,提问作者Kennedy Owusu
相关产品推荐
相关产品推荐

