-
Notifications
You must be signed in to change notification settings - Fork 0
/
assignment3_q2.dart
229 lines (201 loc) · 5.44 KB
/
assignment3_q2.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Album App',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: const AlbumList(),
);
}
}
class AlbumList extends StatefulWidget {
const AlbumList({Key? key}) : super(key: key);
@override
_AlbumListState createState() => _AlbumListState();
}
class _AlbumListState extends State<AlbumList> {
late Future<List<Album>> futureAlbums;
@override
void initState() {
super.initState();
futureAlbums = fetchAlbums();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Album App'),
),
body: Center(
child: FutureBuilder<List<Album>>(
future: futureAlbums,
builder: (context, snapshot) {
if (snapshot.hasData) {
return AlbumListView(albums: snapshot.data!);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddAlbumScreen(),
),
).then((value) {
setState(() {
futureAlbums = fetchAlbums();
});
});
},
child: const Icon(Icons.add),
),
);
}
}
class AlbumListView extends StatefulWidget {
final List<Album> albums;
const AlbumListView({Key? key, required this.albums}) : super(key: key);
@override
_AlbumListViewState createState() => _AlbumListViewState();
}
class _AlbumListViewState extends State<AlbumListView> {
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: widget.albums.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(widget.albums[index].title),
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () {
_deleteAlbum(widget.albums[index].id);
},
),
);
},
);
}
void _deleteAlbum(int id) {
try {
deleteAlbum(id);
setState(() {
widget.albums.removeWhere((album) => album.id == id);
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Album deleted'),
),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Failed to delete album'),
),
);
}
}
}
class AddAlbumScreen extends StatefulWidget {
const AddAlbumScreen({Key? key}) : super(key: key);
@override
_AddAlbumScreenState createState() => _AddAlbumScreenState();
}
class _AddAlbumScreenState extends State<AddAlbumScreen> {
final TextEditingController titleController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add Album'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: titleController,
decoration: const InputDecoration(
labelText: 'Album Title',
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
await addAlbum(titleController.text);
Navigator.pop(context);
},
child: const Text('Add Album'),
),
],
),
),
);
}
}
Future<List<Album>> fetchAlbums() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
if (response.statusCode == 200) {
return (jsonDecode(response.body) as List)
.map((data) => Album.fromJson(data))
.toList();
} else {
throw Exception('Failed to load albums');
}
}
Future<void> addAlbum(String title) async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
if (response.statusCode != 201) {
throw Exception('Failed to add album');
}
}
Future<void> deleteAlbum(int id) async {
final response = await http.delete(
Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
if (response.statusCode != 200) {
throw Exception('Failed to delete album');
}
}
class Album {
final int id;
final int userId;
final String title;
const Album({
required this.id,
required this.userId,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
id: json['id'] as int,
userId: json['userId'] as int,
title: json['title'] as String,
);
}
}