-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.dart
98 lines (86 loc) · 2.11 KB
/
main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(HttpApp());
}
class Post {
final int userId;
final int id;
final String title;
Post({
this.userId,
this.id,
this.title,
});
factory Post.fromJSON(Map<String, dynamic> json) {
return Post(
id: json['id'],
userId: json['userId'],
title: json['title'],
);
}
}
class HttpApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HttpExampleWidget(),
);
}
}
class HttpExampleWidget extends StatefulWidget {
@override
_HttpExampleWidgetState createState() => _HttpExampleWidgetState();
}
class _HttpExampleWidgetState extends State<HttpExampleWidget> {
List<Post> _posts = [];
void _fetchPosts() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts');
final List<Post> parsedResponse = jsonDecode(response.body)
.map<Post>((json) => Post.fromJSON(json))
.toList();
setState(() {
_posts.clear();
_posts.addAll(parsedResponse);
});
}
void _createPost() async {
final response = await http.post(
'https://jsonplaceholder.typicode.com/posts',
body: jsonEncode(
{
'title': 'foo',
'body': 'bar',
'userId': 1,
},
),
headers: {'Content-Type': "application/json"},
);
final Post parsedResponse = Post.fromJSON(jsonDecode(response.body));
// Use the parsedResponse to diplay the newly created post.
}
@override
void initState() {
super.initState();
_fetchPosts();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ListView.builder(
itemCount: this._posts.length,
itemBuilder: (context, index) {
final post = this._posts[index];
return ListTile(
title: Text(post.title),
subtitle: Text('Id: ${post.id} UserId: ${post.userId}'),
);
},
),
),
);
}
}