-
Notifications
You must be signed in to change notification settings - Fork 1
/
many_to_many.dart
390 lines (362 loc) · 12.1 KB
/
many_to_many.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import 'dart:math';
import 'package:example/eloquents/class.dart';
import 'package:example/eloquents/student.dart';
import 'package:example/models/class.dart';
import 'package:example/models/student.dart';
import 'package:flutter/material.dart';
class ManyToManyWidget extends StatefulWidget {
const ManyToManyWidget({Key? key}) : super(key: key);
@override
State<ManyToManyWidget> createState() => _ManyToManyWidgetState();
}
const studentNames = [
'Student A',
'Student B',
'Student C',
'Student D',
'Student E'
];
const classroomNames = [
'Class A',
'Class B',
'Class C',
'Class D',
'Class E',
];
class _ManyToManyWidgetState extends State<ManyToManyWidget> {
final studentEloquent = StudentEloquent();
final classEloquent = ClassEloquent();
final List<Student> students = [];
final List<Class> classes = [];
int selectedStudentIndex = -1;
int selectedClassIndex = -1;
@override
void initState() {
init();
super.initState();
}
init() async {
await loadClasses();
await loadStudents();
// var country = Country(id: 1, name: 'UK');
// await country.save();
// var query = await country.users();
// var users = await userEloquent.get();
// if (users != null && users.isNotEmpty) {
// var user = User.fromDB(users[1]);
// await query.attach(user, extras: {
// 'createdAt': "'${DateTime.now().toIso8601String()}'",
// 'updatedAt': "'${DateTime.now().toIso8601String()}'",
// });
// await query.detach(model: User.fromDB(users[1]));
// }
// print(await (await country.users()).get());
}
showSnack(String message, {Duration? duration}) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
duration: duration ?? const Duration(milliseconds: 600),
));
}
createStudent() async {
String name = studentNames[Random().nextInt(studentNames.length)];
await studentEloquent.updateOrCreate(check: {
'name': name,
}, inserts: {
'createdAt': DateTime.now().toIso8601String(),
'updatedAt': DateTime.now().toIso8601String(),
});
await loadStudents();
}
createClass() async {
String name = classroomNames[Random().nextInt(classroomNames.length)];
await classEloquent.updateOrCreate(check: {
'name': name,
}, inserts: {
'createdAt': DateTime.now().toIso8601String(),
'updatedAt': DateTime.now().toIso8601String(),
});
await loadClasses();
}
attach(Class classroom, Student student) async {
var query = await classroom.getStudents();
var result = await query.attach(student, extras: {
'createdAt': DateTime.now().toIso8601String(),
'updatedAt': DateTime.now().toIso8601String(),
});
showSnack('Attach result: $result');
loadClasses();
}
detach(Class classroom, Student student) async {
var query = await classroom.getStudents();
var result = await query.detach(model: student);
showSnack('detach result: $result');
loadClasses();
}
detachAll(Class classroom) async {
var query = await classroom.getStudents();
var result = await query.detach();
showSnack('detach result: $result');
loadClasses();
}
// create() async {
// if (users.isEmpty) {
// showSnack('Empty User');
// return;
// }
// // var data = await carEloquent.create({
// // 'name': countryNames[Random().nextInt(countryNames.length)],
// // 'user_id': users[Random().nextInt(users.length)].id,
// // 'createdAt': DateTime.now().toIso8601String(),
// // 'updatedAt': DateTime.now().toIso8601String()
// // });
// // showSnack('Created id - $data');
// loadUsers();
// }
loadStudents() async {
var data = await studentEloquent.all();
updateStudentsState(data);
}
updateStudentsState(List<Map<String, Object?>>? data) async {
if (data == null) {
showSnack('Empty');
}
students.clear();
var temp = <Student>[];
for (var row in data!) {
temp.add(Student.fromDB(row));
}
setState(() {
students.addAll(temp);
});
}
loadClasses() async {
var data = await classEloquent.all();
updateClassState(data);
}
updateClassState(List<Map<String, Object?>>? data) async {
if (data == null) {
showSnack('Empty');
}
classes.clear();
var temp = <Class>[];
for (var row in data!) {
temp.add(await Class.withStudents(row));
}
setState(() {
classes.addAll(temp);
});
}
// filterCars() async {
// User user = users[Random().nextInt(users.length)];
// showSnack(
// 'Filtering for cars which ${user.name} owns ... ',
// );
// }
// delete() async {
// if (users.isEmpty) {
// showSnack('Empty car');
// return;
// }
// // var data = await carEloquent.where('id', cars.first.id.toString()).delete();
// // showSnack('Delete rows - $data');
// // loadCars();
// }
// search() async {
// if (users.isEmpty) {
// showSnack('Empty user');
// }
// users.clear();
// User user = users[Random().nextInt(users.length)];
// showSnack('Searching for "F" cars which ${user.name} owns ... ',
// duration: const Duration(milliseconds: 1500));
// var data = await (await user.getCars()).search('F');
// List<String> searchCarIds = data.map((e) => e['id'].toString()).toList();
// showSnack('Search rows - ${data.length}');
// List<User> temp = [];
// for (var user in users) {
// if (user.cars.isNotEmpty &&
// user.cars
// .where((element) => searchCarIds.contains(element.id.toString()))
// .isNotEmpty) {
// temp.add(user);
// }
// }
// setState(() {
// users.addAll(temp);
// });
// }
// orderDesc() async {
// User user = users[Random().nextInt(users.length)];
// showSnack('Ordering desc for ${user.name}',
// duration: const Duration(milliseconds: 2000));
// var data = await (await user.getCars()).orderByDesc('name').get();
// int index = users.indexOf(user);
// // List<Car> temp = [];
// // user.cars = [];
// // if (data != null) {
// // for (var car in data) {
// // temp.add(Car.fromDB(car));
// // }
// // }
// // user.cars = temp;
// setState(() {
// users[index] = user;
// });
// }
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return SingleChildScrollView(
child: SizedBox(
width: size.width * 0.95,
height: size.height,
child: SingleChildScrollView(
controller: ScrollController(),
child: Column(children: [
const SizedBox(height: 10),
const Text('Classes'),
const SizedBox(height: 10),
SizedBox(
height: classes.length * 80,
width: size.width * 0.7,
child: buildClassLists(),
),
const Text('Students'),
const SizedBox(height: 10),
SizedBox(
height: students.length * 80,
width: size.width * 0.7,
child: buildStudentLists(),
),
const SizedBox(height: 10),
SizedBox(
height: size.height * 0.6,
width: size.width * 0.7,
child: ListView.builder(
itemCount: classes.length,
itemBuilder: (_, int index) {
Class classroom = classes[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
classroom.name,
style: const TextStyle(
color: Colors.blue, fontSize: 20),
),
const SizedBox(height: 10),
SizedBox(
height: classroom.students.length * 60,
child: ListView.builder(
physics: const NeverScrollableScrollPhysics(),
itemCount: classroom.students.length,
itemBuilder: (context, index) {
Student student = classroom.students[index];
return ListTile(
title: Text('- ' + student.name),
);
}),
)
],
);
})),
SizedBox(
height: size.height * 0.2,
width: size.width * 0.7,
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
ElevatedButton(
onPressed: createStudent,
child: const Text('Create Student')),
ElevatedButton(
onPressed: createClass,
child: const Text('Create Class')),
ElevatedButton(
onPressed:
selectedClassIndex != -1 && selectedStudentIndex != -1
? () => attach(classes[selectedClassIndex],
students[selectedStudentIndex])
: null,
child: const Text('Attach Student to class')),
ElevatedButton(
onPressed:
selectedClassIndex != -1 && selectedStudentIndex != -1
? () => detach(classes[selectedClassIndex],
students[selectedStudentIndex])
: null,
child: const Text('Detach Student from class')),
ElevatedButton(
onPressed: selectedClassIndex != -1
? () => detachAll(classes[selectedClassIndex])
: null,
child: const Text('Detach all from selected class')),
// ElevatedButton(
// onPressed: orderDesc, child: const Text('Order desc')),
ElevatedButton(onPressed: init, child: const Text('Reload')),
],
),
),
const SizedBox(height: 20),
]),
),
),
);
}
Widget buildStudentLists() {
return ListView.separated(
controller: ScrollController(),
itemBuilder: (context, index) {
return ListTile(
leading: Checkbox(
value: selectedStudentIndex == index,
onChanged: (value) {
if (value != null) {
if (value) {
setState(() {
selectedStudentIndex = index;
});
} else {
setState(() {
selectedStudentIndex = -1;
});
}
}
},
),
title: Text(students[index].name),
);
},
separatorBuilder: (_, __) => const SizedBox(height: 10),
itemCount: students.length);
}
Widget buildClassLists() {
return ListView.separated(
controller: ScrollController(),
itemBuilder: (context, index) {
return ListTile(
leading: Checkbox(
value: selectedClassIndex == index,
onChanged: (value) {
if (value != null) {
if (value) {
setState(() {
selectedClassIndex = index;
});
} else {
setState(() {
selectedClassIndex = -1;
});
}
}
},
),
title: Text(classes[index].name),
);
},
separatorBuilder: (_, __) => const SizedBox(height: 10),
itemCount: classes.length);
}
}