Flutter加载个人资料页出现Null check operator used on a null value错误
解决
Null check operator used on a null value错误 错误根源
API请求还没返回时,profileResponse初始值是null,但你在build方法的TextSelection.collapsed里直接用profileResponse!.userTO!.firstName.length这种强制解包操作——这就是报错的核心原因。你只在fetchData里做了空校验,却没处理UI渲染时的初始空值情况。
修复步骤
1. 修复build中的强制解包
把所有依赖profileResponse的强制解包替换为空安全的链式调用+空合并运算符,确保null时返回默认值:
@override Widget build(BuildContext context) { return Container( child: Column( children: [ Container( child: TextField( controller: TextEditingController.fromValue( TextEditingValue( text: fullName, selection: TextSelection.collapsed( // 空安全获取长度,null时返回0 offset: profileResponse?.userTO?.firstName?.length ?? 0, ), ), ), ), ), Container( child: TextField( controller: TextEditingController.fromValue( TextEditingValue( text: username, selection: TextSelection.collapsed( offset: profileResponse?.userTO?.username?.length ?? 0, ), ), ), ), ), Container( child: TextField( controller: TextEditingController.fromValue( TextEditingValue( text: email, selection: TextSelection.collapsed( offset: profileResponse?.userTO?.email?.length ?? 0, ), ), ), ), ), Container( margin: const EdgeInsets.only(bottom: 16), child: TextField( controller: TextEditingController.fromValue( TextEditingValue( text: phoneNumber, selection: TextSelection.collapsed( offset: phoneNumber.length, ), ), ), ), ), ], ), ); }
2. 优化fetchData的赋值逻辑
用空安全语法简化重复的if-else判断:
Future<void> fetchData() async { try { final response = await getProfileDetails(); if (response?.statusCode == 200) { Map<String, dynamic> parsedData = jsonDecode(response!.body); setState(() { profileResponse = ProfileResponse.fromJson(parsedData); // 简化手机号赋值 phoneNumber = profileResponse?.phoneList.isNotEmpty == true ? profileResponse!.phoneList[0].phoneNumber : ""; // 简化姓名拼接 final firstName = profileResponse?.userTO?.firstName ?? ""; final lastName = profileResponse?.userTO?.lastName ?? ""; fullName = "$firstName $lastName".trim(); // 简化用户名和邮箱赋值 username = profileResponse?.userTO?.username ?? ""; email = profileResponse?.userTO?.email ?? ""; }); } else { // 处理错误状态 } } catch (error) { // 处理异常 } }
3. 可选:添加加载状态
在API请求过程中显示加载指示器,避免用户看到未初始化的UI:
// 新增加载状态变量 bool isLoading = true; Future<void> fetchData() async { try { setState(() => isLoading = true); // 请求开始标记加载中 final response = await getProfileDetails(); // ... 原有逻辑 ... } catch (error) { // ... 异常处理 ... } finally { setState(() => isLoading = false); // 请求结束取消加载状态 } } @override Widget build(BuildContext context) { if (isLoading) { return const Center(child: CircularProgressIndicator()); } return Container( // ... 原有UI代码 ... ); }
内容的提问来源于stack exchange,提问作者Sreejith Sree
相关产品推荐
相关产品推荐

