skip to Main Content

I have an ordering application. after user create account i can see name and address in firebase table. How can I save the user’s name and address in firebase after clicking the place order button? Or is there another way to receive the order?

TextButton kayitButon(BuildContext context) {
return TextButton(
  onPressed: () async {
    AuthService().registerUser(kadi: nameController.text, sifre: sifreController.text, adres: adresController.text);
    userData = {
      "name": nameController.text,
      "sifre": sifreController.text,
      "adres": adresController.text
    };
    await kullaniciRef.doc(nameController.text).set(userData);
    if (formkey.currentState!.validate()) {
      formkey.currentState!.save();
      try {
        await fireBaseAuth.createUserWithEmailAndPassword(
          email: kadi,
          password: sifre,
        );
        formkey.currentState!.reset();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text("Kayıt İşlemi Başarılı"),
          ),
        );

        Navigator.pushReplacementNamed(context, "/loginpage");
      } catch (e) {
        print(e.toString());
      }
    }
  },
  child: Container(
    padding: const EdgeInsets.all(24),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(16),
      color: const Color.fromARGB(255, 83, 188, 83),
    ),
    child: const Text(
      "Kayıt Ol",
      style: TextStyle(
        color: Colors.white,
        // fontWeight: FontWeight.bold,
        fontSize: 20,
      ),
    ),
  ),
);

}

2

Answers


  1. Inside the "Place Order" button’s onPressed callback, you can save the user’s name and address to Firebase using the FirebaseFirestore class:

      void placeOrder(String name, String address) {
      FirebaseFirestore.instance.collection('orders').add({
        'name': name,
        'address': address,
    // Add more order details as needed
      }).then((value) {
        // Order saved successfully
        print('Order placed successfully!');
     }).catchError((error) {
        // Error occurred while saving the order
       print('Error placing order: $error');
     });
    

    }

    In this example, the placeOrder function takes the user’s name and address as arguments. It uses the FirebaseFirestore instance to access the ‘orders’ collection and adds a new document with the user’s name and address. You can include additional order details by adding more key-value pairs to the document.

    The then method is called when the order is saved successfully, and the catchError method is called if there’s an error during the saving process.

    You can call this placeOrder function when the user clicks the "Place Order" button, passing the user’s name and address as arguments.

    This approach allows you to store the user’s order information in Firebase Firestore, making it accessible for further processing or retrieval.

    Login or Signup to reply.
  2. 1.Ensure that the user is logged in before they can place an order. You can do this by implementing a login system using Firebase Authentication or any other authentication mechanism. Make sure to handle user authentication and obtain the necessary user information (username, address) when the user logs in.

    2.Once the user is logged in, you should have access to their username and address. You can use this information to pass it to the placeOrder function you provided.

    3.Before calling the placeOrder function, gather the information about the products the user added to the cart. You may have this information stored in your app’s state or a separate data structure.

    4.After collecting all the required information (username, address, and cart products), you can call the placeOrder function with the appropriate data.

            // Function to place an order
        void placeOrder(String name, String address, List<Product> 
        cartProducts) 
        {
          FirebaseFirestore.instance.collection('orders').add({
            'name': name,
            'address': address,
            'products': cartProducts.map((product) => 
          product.toMap()).toList(),
          }).then((value) {
          // Order saved successfully
             print('Order placed successfully!');
          }).catchError((error) {
            // Error occurred while saving the order
            print('Error placing order: $error');
          });
        }
    
        // Example of a Product class
        class Product {
          final String name;
          final double price;
    
          Product(this.name, this.price);
    
          Map<String, dynamic> toMap() {
            return {
              'name': name,
              'price': price,
              // Add other product details as needed
             };
          }
        }
    
        // Example usage
        void onOrderButtonPressed(User currentUser, List<Product> 
        cartProducts) {
         String username = currentUser.displayName; 
    
        // Replace with  the appropriate way to get the user's username
          String address = currentUser.address; 
    
         // Replace with the appropriate way to get the user's address
    
          placeOrder(username, address, cartProducts);
       }
    

    Please note that the code above assumes you have a class Product to represent the products in the cart, and a User class representing the logged-in user with their display name and address. You will need to adjust the code to fit the structure of your app and authentication system.

    Remember to replace User currentUser with the appropriate way of accessing the current user information from your authentication system. Also, ensure that the Product class includes all the necessary product details you want to save in the Firestore order document.

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