【发布时间】:2020-12-10 20:26:39
【问题描述】:
我通过从 unsplash 服务创建一个简单的照片库并尝试从 https://api.unsplash.com/photos 获取照片列表来学习 Flutter。
我收到运行时错误:
type 'Future<dynamic>' is not a subtype of type 'FutureOr<List<Photo>>'
虽然如果我打印一个列表而不是返回它,我会在控制台中获得 Photo 实例的列表。 我的代码有什么问题以及如何正确处理?
我的照片模型如下所示:
class Photo {
final String id;
final String title;
final String username;
final String url;
Photo({this.id, this.title, this.username, this.url});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'],
title: json['alt_description'],
username: json['user']['name'],
url: json['urls']['raw']);
}
}
我的api数据源:
import 'package:http/http.dart' as http;
import 'dart:convert';
class UnsplashApi {
final String _clientId =
"84y4hgje4ac868c2646c0eddjhfedihdhff612b04c264f3374c97fff98ed253dc9";
Future<String> _fetch(String url) async {
try {
url = buildUrl(url);
var response = await http.get(url);
if (response.statusCode == 200) {
return response.body;
}
} catch (e) {
print(e);
}
}
Future<dynamic> fetchDataByUrl(String url) async {
var data = await _fetch(url);
try {
return json.decode(data);
} catch (e) {
print('Bad content, could not decode JSON');
}
}
String buildUrl(url) {
return url.contains('?')
? url + '&client_id=$_clientId'
: url + '?client_id=$_clientId';
}
}
我的仓库合约(接口):
import 'package:unsplash/domain/models/photo.dart';
abstract class PhotosRepository {
Future<List<Photo>> getPhotosList();
}
我的 Unsplash 照片存储库:
import 'package:unsplash/domain/models/photo.dart';
import 'package:unsplash/domain/repositories/photos_repository.dart';
import 'package:unsplash/infrastructure/data_sources/unsplash_api.dart';
class UnsplashPhotosRepository implements PhotosRepository {
final UnsplashApi _api;
final String _url = 'https://api.unsplash.com/photos';
UnsplashPhotosRepository(this._api);
@override
Future<List<Photo>> getPhotosList() async {
var result = _api.fetchDataByUrl(_url).then((data) {
var list = data?.map((el) => Photo.fromJson(el)).toList();
return list;
});
return result;
}
}
我的测试:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:unsplash/infrastructure/data_sources/unsplash_api.dart';
import 'package:unsplash/infrastructure/repositories/unsplash_photos_repository.dart';
void main() {
group('Unsplash api', () {
test('should get search results', () async {
final api = UnsplashApi();
var result = await UnsplashPhotosRepository(api).getPhotosList();
print(result.runtimeType);
expect(result.isEmpty, false);
});
});
}
【问题讨论】:
-
错误在哪一行?哪个文件?
-
错误出在 UnsplashPhotosRepository 的 getPhotosList 方法上,该行是我们返回结果的地方(方法的最后一行)。
标签: json flutter dart async-await future