Skip to content

Instantly share code, notes, and snippets.

@mhadaily
Created August 21, 2020 13:30
Show Gist options
  • Save mhadaily/d721979393dd031062d9e1674747762d to your computer and use it in GitHub Desktop.
Save mhadaily/d721979393dd031062d9e1674747762d to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'package:http/http.dart' as http;
abstract class PhotosRepository {
Future<List<Photo>> getPhotosList();
}
class Photo {
Photo({
this.id,
this.title,
this.username,
this.url,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'] as String,
title: json['alt_description'] as String,
username: json['user']['name'] as String,
url: json['urls']['raw'] as String,
);
}
final String id;
final String title;
final String username;
final String url;
@override
String toString() {
return '''$id, $title, $username, $url''';
}
}
class UnsplashApi {
final String _clientId = "xxxxxxxxxxxxx";
Future<String> _fetch(String url) async {
try {
url = buildUrl(url);
final http.Response response = await http.get(url);
if (response.statusCode == 200) {
return response.body;
}
return null;
} catch (e) {
print(e);
return null;
}
}
Future<dynamic> fetchDataByUrl(String url) async {
final String data = await _fetch(url);
try {
return json.decode(data);
} catch (e) {
print('Bad content, could not decode JSON $e');
}
}
String buildUrl(String url) {
return url.contains('?') ? '$url&client_id=$_clientId' : '$url?client_id=$_clientId';
}
}
class UnsplashPhotosRepository implements PhotosRepository {
UnsplashPhotosRepository(this._api);
final UnsplashApi _api;
final String _url = 'https://api.unsplash.com/photos';
@override
Future<List<Photo>> getPhotosList() async {
final dynamic result = await _api.fetchDataByUrl(_url);
return (result as List<dynamic>)?.map((dynamic el) => Photo.fromJson(el as Map<String, dynamic>))?.toList();
}
}
void main() {
(() async {
final List<Photo> m = await UnsplashPhotosRepository(UnsplashApi()).getPhotosList();
print(m);
}());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment