You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter注册功能报错:Text widget需传入非空String

问题解决:Flutter注册功能的非空字符串错误

核心错误点

你的代码里存在两个关键问题导致报错:

  1. HTTP响应属性大小写错误
    http.Response的内容属性是小写的body,你代码里写成了大写的Body。response.Body是未定义属性,会返回null,这会引发连锁问题:

    • response.Body != ""的判断永远为false,直接进入错误分支
    • 若尝试解析response.Body,会传入null触发空值异常,进而导致Text widget的非空校验失败
  2. 错误分支的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:15:27