import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Add Subcollections to Existing Departments',
home: AddSubcollectionsPage(),
);
}
}
class AddSubcollectionsPage extends StatelessWidget {
// List of department names (existing documents in 'departments' collection)
final List<String> collectionsToDelete = [
'Biology',
'Chemistry',
'Computer Science and Engineering',
'Electrical and Electronic Engineering',
'Mathematics',
'Physics',
];
// List of subcollections for each department
final List<String> subCollections = [
'1st year',
'2nd year',
'3rd year',
'4th year',
'MS',
'Files',
];
// Method to add subcollections under each existing department
Future<void> addSubcollections() async {
try {
// Reference to the 'departments' collection
CollectionReference departments = FirebaseFirestore.instance.collection('departments');
for (var department in collectionsToDelete) {
// Reference to the department document
DocumentReference departmentDoc = departments.doc(department);
// Check if the department document exists
var docSnapshot = await departmentDoc.get();
if (docSnapshot.exists) {
// Create subcollections under the department
for (var subCollection in subCollections) {
// Add a document to each subcollection
await departmentDoc.collection(subCollection).doc('example').set({
'name': subCollection,
'createdAt': Timestamp.now(),
});
print('Subcollection $subCollection created under department $department.');
}
} else {
print('Department $department does not exist.');
}
}
} catch (e) {
print('Error adding subcollections: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add Subcollections to Existing Departments'),
),
body: Center(
child: Text('Press the button to add subcollections under each department'),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await addSubcollections();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Subcollections added to existing departments!')),
);
},
child: Icon(Icons.add),
tooltip: 'Add Subcollections',
),
);
}
}