Advertisement
anik11556

firebase add department

Jan 3rd, 2025 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.12 KB | None | 0 0
  1. import 'package:cloud_firestore/cloud_firestore.dart';
  2. import 'package:firebase_core/firebase_core.dart';
  3. import 'package:flutter/material.dart';
  4.  
  5. void main() async {
  6.   WidgetsFlutterBinding.ensureInitialized();
  7.   await Firebase.initializeApp();
  8.   runApp(MyApp());
  9. }
  10.  
  11. class MyApp extends StatelessWidget {
  12.   @override
  13.   Widget build(BuildContext context) {
  14.     return MaterialApp(
  15.       title: 'Firebase Create Department Collection',
  16.       home: CreateDepartmentsPage(),
  17.     );
  18.   }
  19. }
  20.  
  21. class CreateDepartmentsPage extends StatelessWidget {
  22.   // List of department names to be added as document IDs
  23.   final List<String> collectionsToDelete = [
  24.     'Biology',
  25.     'Chemistry',
  26.     'Computer Science and Engineering',
  27.     'Electrical and Electronic Engineering',
  28.     'Mathematics',
  29.     'Physics',
  30.   ];
  31.  
  32.   // Method to create a department collection with documents
  33.   Future<void> createDepartments() async {
  34.     try {
  35.       // Reference to the 'departments' collection
  36.       CollectionReference departments = FirebaseFirestore.instance.collection('departments');
  37.  
  38.       for (var department in collectionsToDelete) {
  39.         // Add a document with the department name as the document ID
  40.         await departments.doc(department).set({
  41.           'name': department,
  42.           'createdAt': Timestamp.now(),
  43.         });
  44.         print('Department $department added with document ID: $department');
  45.       }
  46.     } catch (e) {
  47.       print('Error creating departments: $e');
  48.     }
  49.   }
  50.  
  51.   @override
  52.   Widget build(BuildContext context) {
  53.     return Scaffold(
  54.       appBar: AppBar(
  55.         title: Text('Create Department Collection'),
  56.       ),
  57.       body: Center(
  58.         child: Text('Press the button to create the department collection'),
  59.       ),
  60.       floatingActionButton: FloatingActionButton(
  61.         onPressed: () async {
  62.           await createDepartments();
  63.           ScaffoldMessenger.of(context).showSnackBar(
  64.             SnackBar(content: Text('Departments collection created!')),
  65.           );
  66.         },
  67.         child: Icon(Icons.add),
  68.         tooltip: 'Create Departments',
  69.       ),
  70.     );
  71.   }
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement