Flutter运行报The getter 'isNotEmpty' was called on null错误如何解决?
错误原因
报错核心原因是 profileData.photoUrl 字段为null,你没有做空判断就直接调用了isNotEmpty属性,Dart中null对象没有任何属性和方法,因此触发了运行时异常。
修复方案
可以用Dart的空安全调用符?.配合空默认值??处理空值场景,修改后的代码如下:
Widget _profileInfo(Users profileData) { return Padding( padding: const EdgeInsets.all(15.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ CircleAvatar( backgroundColor: Colors.grey, radius: 50.0, // 新增空值判断逻辑 backgroundImage: (profileData.photoUrl?.isNotEmpty ?? false) ? NetworkImage(profileData.photoUrl) : AssetImage("images/user.png"), ) ], ), SizedBox( height: 10.0, ), Text( // userName也可按同样逻辑加空保护,避免同类报错 profileData.userName ?? "默认用户名", style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold), ), SizedBox( height: 10.0, ), _profileEditButton(), SizedBox( height: 10.0, ), _logoutButton(), ], ), ); }
逻辑说明
profileData.photoUrl?.isNotEmpty:如果photoUrl为null,这里直接返回null,不会触发调用异常?? false:如果前面的判断结果为null,就用false作为默认值,保证三目运算符的判断条件始终是布尔值- 其他需要读取
profileData字段的位置也建议按同样逻辑加空保护,避免同类空调用报错。
内容的提问来源于stack exchange,提问作者Nisa Efendioglu
相关产品推荐
相关产品推荐

