cofounderella/lib/forms/skills_form.dart

143 lines
4.8 KiB
Dart

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../constants.dart';
import '../../enumerations.dart';
import '../../services/auth/auth_service.dart';
import 'profile_category_form.dart';
class SkillsForm extends StatelessWidget {
SkillsForm({
super.key,
required this.isRegProcess,
required this.skillsSought,
});
// get instance of firestore and auth
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final AuthService _authService = AuthService();
final bool isRegProcess;
final bool skillsSought; // flag to toggle offered and sought skills
@override
Widget build(BuildContext context) {
return FutureBuilder<List<SkillOption>>(
future: getSkillsFromFirebase(), // Fetch skills from Firebase
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
// Show loading indicator while fetching data
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List<SkillOption>? userSkills = snapshot.data;
return ProfileCategoryForm(
title: 'Skills',
header:
skillsSought ? 'Skills you are looking for' : 'Your own skills',
description: skillsSought
? 'Choose up to 3 areas you are looking for in a co-founder'
: 'Select up to 3 areas in which you are skilled',
saveButtonText: isRegProcess ? 'Save and continue' : 'Save',
options: SkillOption.values.toList(), // Convert enum values to list
minSelections: 1,
maxSelections: 3,
preSelectedOptions:
userSkills ?? [], // Pass pre-selected skills to the form
onSave: (selectedOptions) async {
// Handle saving selected options
bool success = await saveSkillsToFirebase(
selectedOptions.cast<SkillOption>());
// Then navigate to another screen or perform any other action???
if (context.mounted) {
if (success) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SkillsForm(
isRegProcess: isRegProcess,
skillsSought: true,
),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Failed to save user skills.'),
),
);
}
}
},
);
}
},
);
}
Future<List<SkillOption>> getSkillsFromFirebase() async {
// Fetch skills from Firestore
String currentUserId = _authService.getCurrentUser()!.uid;
DocumentSnapshot userDoc = await _firestore
.collection(Constants.dbCollectionUsers)
.doc(currentUserId)
.get();
if (userDoc.exists && userDoc.data() != null) {
Map<String, dynamic> userData =
userDoc.data()! as Map<String, dynamic>; // Explicit cast
List<dynamic>? skills;
if (skillsSought) {
skills = userData[Constants.dbFieldUsersSkillsSought];
} else {
skills = userData[
Constants.dbFieldUsersSkills]; //as List<dynamic>?; // Explicit cast
}
if (skills != null && skills.isNotEmpty) {
// Convert skills from strings to enum values
List<SkillOption> userSkills = skills
.map((skill) => SkillOption.values
.firstWhere((x) => x.toString() == 'SkillOption.$skill'))
.toList();
return userSkills;
}
}
return [];
}
Future<bool> saveSkillsToFirebase(List<SkillOption> selectedOptions) async {
try {
String currentUserId = _authService.getCurrentUser()!.uid;
// Convert enum values to strings, removing leading EnumType with split
List<String> skills = selectedOptions
.map((option) => option.toString().split('.').last)
.toList();
// Update the corresponding 'skills' field in the user's document
String keyToUpdate = skillsSought
? Constants.dbFieldUsersSkillsSought
: Constants.dbFieldUsersSkills;
_firestore
.collection(Constants.dbCollectionUsers)
.doc(currentUserId)
.update({
keyToUpdate: skills,
}).then((_) {
print('$keyToUpdate saved to Firebase: $skills');
}).catchError((error) {
print('Failed to save $keyToUpdate: $error');
});
return true;
} catch (e) {
return false;
}
}
}