Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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: 'Firebase Create Department Collection',
- home: CreateDepartmentsPage(),
- );
- }
- }
- class CreateDepartmentsPage extends StatelessWidget {
- // List of department names to be added as document IDs
- final List<String> collectionsToDelete = [
- 'Biology',
- 'Chemistry',
- 'Computer Science and Engineering',
- 'Electrical and Electronic Engineering',
- 'Mathematics',
- 'Physics',
- ];
- // Method to create a department collection with documents
- Future<void> createDepartments() async {
- try {
- // Reference to the 'departments' collection
- CollectionReference departments = FirebaseFirestore.instance.collection('departments');
- for (var department in collectionsToDelete) {
- // Add a document with the department name as the document ID
- await departments.doc(department).set({
- 'name': department,
- 'createdAt': Timestamp.now(),
- });
- print('Department $department added with document ID: $department');
- }
- } catch (e) {
- print('Error creating departments: $e');
- }
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text('Create Department Collection'),
- ),
- body: Center(
- child: Text('Press the button to create the department collection'),
- ),
- floatingActionButton: FloatingActionButton(
- onPressed: () async {
- await createDepartments();
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(content: Text('Departments collection created!')),
- );
- },
- child: Icon(Icons.add),
- tooltip: 'Create Departments',
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement