Created
August 23, 2020 11:46
-
-
Save buroz/31dfaa0d52d0f27b43aeaa6c35d0975d to your computer and use it in GitHub Desktop.
First things on Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:http/http.dart'; | |
import 'package:flutter/foundation.dart'; | |
const String serviceUrl = 'https://jsonplaceholder.typicode.com'; | |
class HttpCallService extends HttpCallService { | |
String path; | |
HttpCallService(this.path); | |
Future<List<dynamic>> get(String endpoint) async { | |
try { | |
Response res = await get(serviceUrl + this.path + endpoint); | |
return List<dynamic> jsonDecode(res.body); | |
} | |
catch(e) { | |
throw new FormatException(e); | |
} | |
} | |
} | |
class PostDto { | |
final int id; | |
final int userId; | |
final String body; | |
final String title; | |
Post({ | |
@required this.id, | |
@required this.userId, | |
@required this.body, | |
@required this.title, | |
}); | |
factory Post.fromJson(Map<String, dynamic> json) { | |
return Post( | |
id: json['id'] as int, | |
userId: json['userId'] as int, | |
body: json['body'] as String, | |
title: json['title'] as String, | |
); | |
} | |
} | |
class PostService extends HttpCallService { | |
String path; | |
super.HttpCallService(this.path); | |
Future<List<PostDto>> getPosts(String endpoint) async { | |
try { | |
List<dynamic> resJson = await this.HttpCallService.get(endpoint); | |
List<Post> posts = resJson.map((dynamic item) => PostDto.fromJson(item)).toList(); | |
return posts | |
} | |
catch(e) { | |
throw new FormatException(e); | |
} | |
} | |
} | |
void main() { | |
postService = PostService('/posts'); | |
posts =postService.getPosts('/'); | |
posts.forEach((p) => print(p.title)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment