[英]Flutte - JSON deserialized data fetched to FutureBuilder return null value
我正在嘗試通過從 API 獲取的數據通過 FutureBuilder 返回照片的 ListView。 在我的服務中將值添加到 List 並正確分配時,獲取到 List Builder 的值是 null。 我不知道為什么調用服務方法返回 Future<List> 會返回 null 的列表。
我的 model:
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());
},
);
}
}
您遇到此問題的原因是您需要在映射 function 中返回解析的 object。
解決方案 #1 - 將return
關鍵字添加到現有代碼中
return randomPhotos = (json.decode(_response.body) as List).map((i) {
return Photo.fromJson(i); // <-- added return keyword here
}).toList();
解決方案 #2 - 使用箭頭定義回報
此解決方案適合您的代碼,因為您沒有操作照片 object 或映射中的任何其他數據。
return randomPhotos = (json.decode(_response.body) as List).map((i) => Photo.fromJson(i)).toList();
任何一種解決方案都應該有效。 選擇適合您的編碼風格和需求的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.