Flutter渲染API数据时Text组件报非空字符串错误排查
问题根因
报错A non-null String must be provided to a Text widget的触发原因是:你传入Text组件的字符串参数存在null值。GitHub公开仓库接口返回的数据中,description字段不是必填项,未填写描述的仓库该字段会直接返回null,你直接将可能为null的值传给Text组件,就触发了组件的非空校验报错。
另外你的repo.dart文件中重复定义了两次Repo类和All类,会引发类重复定义的编译错误,需要同步清理。
修复方案
1. 修正repo.dart文件
- 删除重复的
Repo、All类定义,仅保留一份即可 - 将可能返回null的
description字段标记为可空类型,JSON解析时增加空值兜底逻辑,修改后完整代码如下:
class Repo { String name; String htmlUrl; int stargazersCount; String? description; // 标记为可空类型,适配接口返回null的场景 Repo( {required this.name, required this.htmlUrl, required this.stargazersCount, this.description}); // description改为非必填参数 factory Repo.fromJson(Map<String, dynamic> json) { return Repo( name: json['name'] ?? '', // 极端场景兜底空字符串 htmlUrl: json['html_url'] ?? '', stargazersCount: json['stargazers_count'] ?? 0, description: json['description'], ); } } class All { List<Repo> repos; All({required this.repos}); factory All.fromJson(List<dynamic> json) { List<Repo> repos = <Repo>[]; repos = json.map((r) => Repo.fromJson(r)).toList(); return All(repos: repos); } }
2. 修正main.dart中的渲染逻辑
- 移除FutureBuilder中冗余的循环组装Repo列表逻辑:
All.fromJson方法已经完成了列表解析,不需要再遍历重新实例化Repo对象,直接使用snapshot.data!.repos即可 - 所有传给Text组件的字段增加空值兜底,避免null传入,将列表渲染部分的Card代码替换为如下内容:
Card( color: Colors.blue[300], child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( r.name, style: const TextStyle(fontSize: 30.0), ), Text(r.stargazersCount.toString()), ], ), Text( r.description ?? '该仓库暂无描述', // null时显示兜底文案 style: const TextStyle(fontSize: 23.0), ), Text(r.htmlUrl), ], ), ), )
效果说明
修改完成后重新运行项目,即使接口返回的仓库描述字段为null,页面也会正常显示兜底文案,不会再触发Text组件的非空报错。
内容的提问来源于stack exchange,提问作者Icaro Moreira
相关产品推荐
相关产品推荐

