Flutter调用Github API报错:期望String类型却得到Null的解决
解决Flutter中Github API数据解析的Null类型错误
问题根源
错误Expected a value of type 'String', but got one of type 'Null'的核心原因:
- Github API返回的部分仓库数据里,
description字段为null,但你的Repo类将description定义为必填的非空String类型,解析JSON时无法将null赋值给非空String,直接触发错误。 - 同时在
_MyHomePageState的build方法中,你错误地将description赋值为htmlUrl,会导致后续展示内容错误。
修复步骤
1. 调整Repo类的字段定义,处理null值
将description改为可空类型,或在解析时给null设置默认值,两种方式选其一即可:
方式1:使用可空字段
class Repo { String name; String htmlUrl; String? description; // 改为可空String类型 Repo({ required this.name, required this.htmlUrl, this.description, // 去掉required修饰符 }); factory Repo.fromJson(Map<String, dynamic> json) { return Repo( name: json['name'] as String, htmlUrl: json['html_url'] as String, description: json['description'] as String?, // 允许null赋值 ); } }
方式2:给非空字段设置默认值
class Repo { String name; String htmlUrl; String description; // 保持非空 Repo({ required this.name, required this.htmlUrl, required this.description, }); factory Repo.fromJson(Map<String, dynamic> json) { return Repo( name: json['name'] as String, htmlUrl: json['html_url'] as String, description: json['description'] as String? ?? '无描述', // null时替换为默认字符串 ); } }
2. 修正MyHomePage中的赋值错误
把循环创建Repo时的description赋值从htmlUrl改为正确的字段:
// 原错误代码 description: snapshot.data!.repos[i].htmlUrl, // 修正后 description: snapshot.data!.repos[i].description,
3. 优化FutureBuilder代码(可选)
无需重新创建Repo列表,直接使用接口返回的列表即可,减少冗余:
if (snapshot.hasData) { return ListView( children: snapshot.data!.repos.map((r) => Card( child: Padding( padding: EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(r.name, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), // 如果用可空字段,需要判断后再展示 if (r.description != null) Text(r.description!), Text(r.htmlUrl, style: TextStyle(color: Colors.blueAccent)), ], ), ), )).toList(), ); }
内容的提问来源于stack exchange,提问作者Sreejith K Pai
相关产品推荐
相关产品推荐

