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

Flutter页面无法显示登录用户姓名问题排查求助

问题排查与解决

问题原因

你的代码中,getData是异步方法,initState执行时会触发第一次Widget构建,此时nomecognome还是初始值(大概率为null)。当异步请求完成并更新nomecognome变量后,没有通知Flutter框架状态发生变化,Widget不会重新构建,因此Text组件无法显示新的内容——终端能打印正确值,说明数据获取流程是正常的。

解决方法

在更新nomecognome时用setState包裹,触发Widget重新渲染:

修改后的getData方法:

void getData() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    code = prefs.getString('code');

    var url = "http://localhost/profilo.php";

    var response = await http.post(Uri.parse(url), body: {
      "username": code,
    });

    var data = jsonDecode(response.body);

    setState(() {
      nomecognome = "WELCOME "+ data['name'] +" "+ data['surname'];
    });

    print(nomecognome);
}

额外优化建议

  • 给nomecognome设置初始加载提示(比如"加载中..."),避免页面显示空白,提升用户体验。
  • 增加异常处理逻辑,比如捕获网络请求失败、数据解析错误等情况,防止程序崩溃。

内容的提问来源于stack exchange,提问作者Cristiano Z

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:02:26