0

I'm trying to create a simple banking app with flutter.I'm creating the user login information myself and trying to auth them with firebase. I already coded the authentication part of the app.Here is the code:

import 'package:banking_app_firebase/screens/customers_info.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

import '../constants.dart';

class LoginScreen extends StatefulWidget {
  static const String id = 'login_screen';
  const LoginScreen({Key? key}) : super(key: key);

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _auth = FirebaseAuth.instance;
  bool showSpinner = false;
  String? email;
  String? password;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Flexible(
                child: Hero(
                  tag: 'logo',
                  child: Container(
                    height: 100,
                    child: Image.network(
                      "https://image.flaticon.com/icons/png/512/662/662622.png",
                    ),
                  ),
                ),
              ),
              SizedBox(height: 20),
              TextField(
                keyboardType: TextInputType.emailAddress,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  email = value;
                },
                decoration:
                    kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
              ),
              SizedBox(
                height: 20,
              ),
              TextField(
                obscureText: true,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  password = value;
                },
                decoration: kTextFieldDecoration.copyWith(
                    hintText: "Enter your password"),
              ),
              SizedBox(
                height: 24,
              ),
              Padding(
                padding: EdgeInsets.symmetric(vertical: 16),
                child: Material(
                  elevation: 5,
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(30),
                  child: MaterialButton(
                    onPressed: () async {
                      setState(() {
                        showSpinner = true;
                      });
                      try {
                        final user = await _auth.signInWithEmailAndPassword(
                            email: email!, password: password!);
                        if (user != null) {
                          Navigator.pushNamed(context, CustomerScreen.id);
                        }
                        setState(() {
                          showSpinner = true;
                        });
                      } catch (e) {
                        print(e);
                      }
                    },
                    height: 42,
                    child: Text(
                      "Login",
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
    ;
  }
}

Sample Users:

enter image description here

However, I don't know how to sync these information with my database so I can reach the data in the database. Here is my example database:

enter image description here

How can I get the informations about customers like name,surname,balance after auth is successful? I mean, how can I tell the Firebase, the auth email and password same as firestore database?

1 Answer 1

3

How can I get the information about customers like name, surname, balance after auth is successful?

I understand that you want to link one document of the customers collection to each user. The classical solution to do so is to use the user uid as the Firestore document ID.

As soon as your user is created, you can get its uid and create the Firestore document, like, for example:

final user = await _auth.signInWithEmailAndPassword(
        email: email!, password: password!
);
if (user != null) {
    await addCustomer(user.uid, email, password);
    Navigator.pushNamed(context, CustomerScreen.id);
}


...


CollectionReference customers = FirebaseFirestore.instance.collection('customers');

Future<void> addCustomer(userID, email, password) {
  return customers
    .doc(userID)
    .set({
      ...
    })
    .then((value) => print("Customer added"))
    .catchError((error) => print("Failed to add customer: $error"));
}

I understand from your comment below that you want to query the customers collection to find the user which has a specific email and password.

This is possible with a query, however I would recommend not using the password value for executing queries. This is a sensitive data that you should avoid using as a query parameter.

Actually you can very well query just by email: since you cannot create two Firebase users with the same email, you are sure that your query will return a unique result (if you didn't create some duplicate documents in the customers collection...).

Sign up to request clarification or add additional context in comments.

4 Comments

I already created users for authentication and database. What I want to do is, when a user logged in, I mean with firebase authentication, I wanted to show the informations who has the same email and password with authenticated user in database. I don't know if I could explain.
Ok, I understand. I'll adapt my answer.
I mean let's say I want to get the name variable as a string where 'email' = email. How can I get this value as a string? ` var name = customers.where('email', isEqualTo: email).get().then();` I tried this, but I think I did not how to reach that data.
Look at the doc on QuerySnapshot. Have also a look at this article from the Firebase Tips & Tricks Medium publication.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.