Asset-Borrowing-App / lib / Project / ProfilePage / EditProfilePage / edit_name.dart
edit_name.dart
Raw
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/Project/ProfilePage/EditProfilePage/edit_profile_page.dart';
import 'package:flutter_application_1/Project/ProfilePage/widgets/appbar_widget.dart';
import 'package:string_validator/string_validator.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../utils/colors.dart';

class EditNameFormPage extends StatefulWidget {
  const EditNameFormPage({Key? key}) : super(key: key);

  @override
  EditNameFormPageState createState() {
    return EditNameFormPageState();
  }
}

class EditNameFormPageState extends State<EditNameFormPage> {
  final _formKey = GlobalKey<FormState>();
  final CollectionReference usersCollection =
      FirebaseFirestore.instance.collection('users');
  final _firstNameController = TextEditingController();
  final _lastNameController = TextEditingController();
    bool isValid = true;


  @override
  void initState() {
    super.initState();
    _firstNameController.addListener(() {});
    _lastNameController.addListener(() {});
  }

  @override
  void dispose() {
    _firstNameController.dispose();
    _lastNameController.dispose();
    super.dispose();
  }

  void clearForm() {
    _firstNameController.clear();
    _lastNameController.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            const SizedBox(
                width: 330,
                child: Text(
                  "Enter Your New Name",
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 40, 16, 0),
                  child: SizedBox(
                    height: 100,
                    width: 150,
                    child: TextFormField(
                      // Handles Form Validation for First Name
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter your first name';
                        } else if (!isAlpha(value)) {
                          return 'Only Letters Please';
                        }
                        return null;
                      },
                      decoration:
                          const InputDecoration(labelText: 'First Name'),
                      controller: _firstNameController,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 40, 16, 0),
                  child: SizedBox(
                    height: 100,
                    width: 150,
                    child: TextFormField(
                      // Handles Form Validation for Last Name
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter your last name';
                        } else if (!isAlpha(value)) {
                          return 'Only Letters Please';
                        }
                        return null;
                      },
                      decoration: const InputDecoration(labelText: 'Last Name'),
                      controller: _lastNameController,
                    ),
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 150),
              child: Align(
                alignment: Alignment.bottomCenter,
                child: SizedBox(
                  width: 330,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: () async {
                      setState(() {
                        isValid = _formKey.currentState!.validate();
                  
                      });
                     if (isValid) {
                        // Get the user ID of the current user
                        final String? uid =
                            FirebaseAuth.instance.currentUser?.uid;

                      if (uid != null) {
                        // Get the DocumentReference of the user's document
                        final DocumentReference userDocRef =
                            usersCollection.doc(uid);

                        final String firstName =
                            _firstNameController.text.trim();
                        final String lastName = _lastNameController.text.trim();

                        // Update the user's document with the new values
                        await userDocRef.update({
                          'firstName': firstName,
                          'lastName': lastName,
                        });

                        // Navigate back to the previous screen
                          // ignore: use_build_context_synchronously
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: ((context) =>
                                      const EditProfilePage())));
                        }
                      } else {
                        // Display an error message
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(
                            content:
                                Text('Error: Please enter First and Last Name'),
                            duration: Duration(seconds: 3),
                          ),
                        );
                      }
                    },
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all<Color>(kGreenColor),
                    ),
                    child: const Text(
                      'Update',
                      style: TextStyle(fontSize: 15),
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}