json - Flutte - 提取到 FutureBuilder 的 JSON 反序列化数据返回空值
问题描述
我正在尝试通过从 API 获取数据的 FutureBuilder 返回照片的 ListView。在我的服务中将值添加到 List 并正确分配时,获取到 List Builder 的值是 null。我不知道为什么调用服务方法返回 Future<List> 会返回 null 列表。
我的模型:
class Photo {
String id;
String photoDesc;
String photoAuthor;
String photoUrlSmall;
String photoUrlFull;
String downloadUrl;
int likes;
Photo(
{this.id,
this.photoDesc,
this.photoAuthor,
this.photoUrlSmall,
this.photoUrlFull,
this.downloadUrl,
this.likes});
Photo.fromJson(Map<String, dynamic> json) {
id = json['id'];
photoDesc = json['description'] != null
? json['description']
: json['alt_description'];
photoAuthor = json['user']['name'] != null
? json['user']['name']
: json['user']['username'];
photoUrlSmall = json['urls']['small'];
photoUrlFull = json['urls']['full'];
downloadUrl = json['links']['download'];
likes = json['likes'];
}
}
我的服务:
Future<List<Photo>> getRandomData1() async {
List<Photo> randomPhotos;
_response = await http.get(Uri.parse(
'$unsplashUrl/photos/random/?client_id=${_key.accessKey}&count=30'));
if (_response.statusCode == 200) {
return randomPhotos = (json.decode(_response.body) as List).map((i) {
Photo.fromJson(i);
print(Photo.fromJson(i).id); // **i.e. printing returns proper values**
}).toList();
} else {
print(_response.statusCode);
throw 'Problem with the get request';
}
}
我的建设者:
class RandomPhotosListView extends StatefulWidget {
@override
_RandomPhotosListViewState createState() => _RandomPhotosListViewState();
}
class _RandomPhotosListViewState extends State<RandomPhotosListView> {
final UnsplashApiClient unsplashApiClient = UnsplashApiClient();
Future _data;
ListView _randomPhotosListView(data) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Text("${data[index]}");
});
}
@override
void initState() {
super.initState();
_data = unsplashApiClient.getRandomData1();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _data,
builder: (context, snapshot) {
print(snapshot.data); // i.e. snapshot.data here is list of nulls
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
print(snapshot.error);
return Text("error: ${snapshot.error}");
} else if (snapshot.hasData) {
return _randomPhotosListView(snapshot.data);
}
return Center(child: CircularProgressIndicator());
},
);
}
}
解决方案
您遇到此问题的原因是您需要在映射函数中返回解析的对象。
解决方案 #1 - 将return
关键字添加到现有代码中
return randomPhotos = (json.decode(_response.body) as List).map((i) {
return Photo.fromJson(i); // <-- added return keyword here
}).toList();
解决方案 #2 - 使用箭头定义回报
此解决方案适合您的代码,因为您没有操作 Photo 对象或映射中的任何其他数据。
return randomPhotos = (json.decode(_response.body) as List).map((i) => Photo.fromJson(i)).toList();
任何一种解决方案都应该有效。选择适合您的编码风格和需求的内容。
推荐阅读
- javascript - 如何让用户更漂亮地在客户端格式化代码?
- reactjs - 如果不支持用户的浏览器,我可以呈现警告消息吗?
- swift - 从 UserDefaults 中检索字符串不起作用
- java - 使用 teamcity 构建时生成工件的示例 java 项目
- python - 可以使用 CNN 的特征图来定位图像中的重要区域吗?
- selenium-webdriver - NUnit:如何根据 [TestFixture(typeof(param))] 中的参数设置测试名称
- excel - 运行 VBA 代码时 Excel 表格不展开,但在其下方键入任何字母时展开
- c# - 使用 ASP.NET MVC 路由之类的路由解析对象
- group-by - Cognos Report Studio - 分组/过滤
- scala - 查找从一个顶点开始的所有路径,直到没有更多的直接后继