skip to Main Content

i try to connect my flutter app to firebase to save user data and authenticat him
the data has been save successfully in firestore but the authentication dosent work
the depandncy was ok beacuse in onther page the authentication is success
i use email passowrd authentication the samplest one

this is my dependencies
i import all the pakage and i do everting as firebase.flutter.dev told me to do
this is my code i delete the UI details
i try to import s

firebase core
firebase auth
cloud firestore

i statr with bulid the connection
and this is the code
in onPressed() i try to send the email and the password that taken in textfilde before

the addUser() is methos to store the details to the firestore

void main() async{
  runApp(MyApp());
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage(), routes: <String, WidgetBuilder>{
      '/AsDocter': (context) => AsDoctor(),
      '/AsPatient': (context) => AsPatient(),
      '/Login': (context) => Login()
    });
  }
}




class AsDoctor extends StatefulWidget {
  @override
  _AsDoctorState createState() => _AsDoctorState();
}

class _AsDoctorState extends State<AsDoctor> {
  String email = ''; // Initialize with an empty string
  String password = ''; // Initialize with an empty string
  String firstName = ''; // Create a variable for the First Name
  String lastName = ''; // Create a variable for the Last Name
  String id = ''; // Create a variable for the ID
  String phoneNumber = ''; // Create a variable for Phone Number
  String city = ''; // Create a variable for the City
  String gender = ''; // Create a variable for Gender
  String license = ''; // Create a variable for License
  String formattedDate = ''; // Initialize with an empty string

  DateTime?
  selectedDate; // Create a DateTime variable to store the selected date
  File? selectedFile; // Create a File variable to store the selected file

  // Function to show the date picker
  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = (await showDatePicker(
      context: context,
      initialDate: selectedDate ?? DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime(2101),
    ))!;
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

  // Function to pick a file
  void _pickFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      setState(() {
        selectedFile = File(result.files.single.path!);
      });
    }
  }
    CollectionReference Doctor = FirebaseFirestore.instance.collection('Doctors');

    // Create a map with the user data
    Future<void> addUser() {
      // Call the user's CollectionReference to add a new user
      return Doctor
          .add({
        'First Name': firstName,
        'Last Name': lastName,
        'ID': id,
        'Email': email,
        'Phone Number': phoneNumber,
        'City': city,
        'Gender': gender,
      })
          .then((value) => print("User Added"))
          .catchError((error) => print("Failed to add user: $error"));
    }

  @override
  Widget build(BuildContext context) {
    String formattedDate = selectedDate != null
        ? "${selectedDate!.year}-${selectedDate!.month.toString().padLeft(2, '0')}-${selectedDate!.day.toString().padLeft(2, '0')}"
        : "Date of Birth";

    return Scaffold(
      appBar: AppBar(
        title: Text('Doctor Page'),
      ),
      body: SingleChildScrollView(
        child: Container(
          width: 430,
          height: 1050,
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(color: Colors.white),
          child: Stack(
            children: [
              Positioned(
                left: -67,
                top: -35,
                child: Container(
                  width: 564,
                  height: 1150,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('img/background.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
              ), // Background
              Positioned(
                left: 20,
                top: 118,
                child: Container(
                  width: 375,
                  height: 949,
                  decoration:
                  BoxDecoration(color: Colors.white.withOpacity(0.5)),
                ),
              ),
              Positioned(
                left: 163,
                top: 65,
                child: Container(
                  width: 108,
                  height: 107,
                  decoration: ShapeDecoration(
                    color: Color(0xFF0A8DD3),
                    shape: CircleBorder(),
                    shadows: [
                      BoxShadow(
                        color: Color(0x3F000000),
                        blurRadius: 4,
                        offset: Offset(0, 4),
                        spreadRadius: 0,
                      )
                    ],
                  ),
                ),
              ),
              // First Name TextBox
              Positioned(
                left: 72,
                top: 201,
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        firstName = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'First Name',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Last Name TextBox
              Positioned(
                left: 72,
                top: 276, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        lastName = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'Last Name',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // ID TextBox
              Positioned(
                left: 72,
                top: 351, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        id = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'ID',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Email TextBox
              Positioned(
                left: 72,
                top: 426, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        email = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'Email',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Phone Number TextBox
              Positioned(
                left: 72,
                top: 501, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        phoneNumber = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'Phone Number',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // City TextBox
              Positioned(
                left: 72,
                top: 576,
                // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        city = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'City',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Gender TextBox
              Positioned(
                left: 72,
                top: 651,
                // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        gender = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'Gender',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // License TextBox
              Positioned(
                left: 72,
                top: 800,
                // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Import License:',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 10),
                      ElevatedButton(
                        onPressed: _pickFile, // Open file picker
                        style: ElevatedButton.styleFrom(
                          primary: Color(0xFF0A8DD3),
                          padding: EdgeInsets.symmetric(
                              vertical: 10, horizontal: 20),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          shadowColor: Color(0x3F000000),
                          elevation: 4,
                        ),
                        child: Text(
                          selectedFile != null
                              ? 'File Selected'
                              : 'Select License File',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              // Password TextBox
              Positioned(
                left: 72,
                top: 726,
                // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    obscureText: true, // For password fields
                    decoration: InputDecoration(
                      hintText: 'Password',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Date of Birth TextBox
              Positioned(
                left: 72,
                top: 876, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          'Date of Birth:',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      SizedBox(width: 10),
                      Expanded(
                        child: TextButton(
                          onPressed: () =>
                              _selectDate(context), // Show date picker
                          child: Text(
                            formattedDate, // Display selected date
                            style: TextStyle(
                              fontSize: 18,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              // Sign In Button
              Positioned(
                left: 90,
                top: 951, // Adjust the top position
                child: ElevatedButton(
                  onPressed: ()  async{
                    addUser();
                    try {
                      final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
                        email: email,
                        password: password,
                      );
                      print('===================================done');
                    } on FirebaseAuthException catch (e) {
                      if (e.code == 'weak-password') {
                        print('The password provided is too weak.');
                      } else if (e.code == 'email-already-in-use') {
                        print('The account already exists for that email.');
                      }
                    } catch (e) {
                      print(e);
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF0A8DD3),
                    padding: EdgeInsets.symmetric(vertical: 15, horizontal: 70),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    shadowColor: Color(0x3F000000),
                    elevation: 4,
                  ),
                  child: Text(
                    'Sign in',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 25,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w900,
                      height: 0,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

2

Answers


  1. It looks like you are trying to create a user using Firebase Authentication (createUserWithEmailAndPassword) after adding user data to Firestore. However, you have some issues in your code that may be causing problems. Here are some suggestions to help you troubleshoot and potentially fix the issues:

    Password Missing: You are using the password variable in createUserWithEmailAndPassword, but the password variable is not being set anywhere in your code. You should capture the password input from the user and set it to the password variable before using it in the authentication.

    Asynchronous Code: Firebase authentication functions are asynchronous, and it’s important to await them. Ensure that you use await when calling createUserWithEmailAndPassword to make sure you wait for the authentication to complete before proceeding.

    Here’s an updated version of your code with these considerations:

    // … (other imports and code)

    class _AsDoctorState extends State {
    // …

    // Password TextBox
    Positioned(
    left: 72,
    top: 726, // Adjust the top position
    child: Container(
    width: 250, // Adjust the width
    child: TextFormField(
    obscureText: true, // For password fields
    onChanged: (value) {
    setState(() {
    password = value; // Capture the password input
    });
    },
    decoration: InputDecoration(
    hintText: ‘Password’,
    fillColor: Colors.white,
    filled: true,
    border: OutlineInputBorder(
    borderRadius: BorderRadius.circular(15.0),
    ),
    ),
    ),
    ),
    ),

    // Sign In Button
    Positioned(
    left: 90,
    top: 951, // Adjust the top position
    child: ElevatedButton(
    onPressed: () async {
    // Capture the password input before adding user and signing in
    addUser();
    try {
    final credential = await FirebaseAuth.instance
    .createUserWithEmailAndPassword(
    email: email,
    password: password, // Use the captured password
    );
    print(‘===================================done’);
    } on FirebaseAuthException catch (e) {
    if (e.code == ‘weak-password’) {
    print(‘The password provided is too weak.’);
    } else if (e.code == ’email-already-in-use’) {
    print(‘The account already exists for that email.’);
    }
    } catch (e) {
    print(e);
    }
    },
    // … (rest of the button styling and text)
    ),
    ),

    // …
    }

    Make sure you capture the user’s password input and set it to the password variable before calling createUserWithEmailAndPassword. Also, ensure that you have Firebase properly configured in your Flutter app, including the necessary Firebase configuration files.

    Login or Signup to reply.
  2. Make Sure, you have enable email and password from firebase admin panel,
    follow below Steps

    1. Open firebase console account.
    2. click All Product, which show in side nav bar.
    3. To see authentication card, click on it.
    4. swipe tab sign-in method, then tap add provider button.
    5. select email and password, see dialog click to enable.

    Then restart your app and try to login also check log cat message

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search