Home > Software engineering >  Flutter Firebase Auth Login is not going to Main Page
Flutter Firebase Auth Login is not going to Main Page

Time:06-26

I was trying to integrate Firebase Authentication into my first Firebase App but when try to log in nothing happens and I got the following message: Notifying id token listeners about user

following is my loginPage.dart:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:untitled/Screens/mainpage.dart';
import 'package:untitled/Screens/registrationpage.dart';
import 'package:untitled/brand_colors.dart';
import 'package:untitled/widgets/TaxiButton.dart';
class LoginPage extends StatefulWidget {
  LoginPage({Key? key, required this.emailController, required this.passwordController}) : super(key: key);
  static const String id = 'login';
  final FirebaseAuth _auth = FirebaseAuth.instance;
  var emailController = TextEditingController();
  var passwordController = TextEditingController();
  void login(BuildContext context) async {
    final FirebaseUser user = (await _auth.signInWithEmailAndPassword(
      email: emailController.text,
      password: passwordController.text,
    ).catchError((ex){
    PlatformException thisEx = ex;
    showSnackBar(thisEx.message.toString());
    })).user;

    if(user != null){
      // verify login
      DatabaseReference userRef = FirebaseDatabase.instance.reference().child('user/${user.uid}');
      userRef.once().then((DataSnapshot snapshot) => {
      if(snapshot.value != null){
          Navigator.pushNamedAndRemoveUntil(context, MainPage.id, (route) => false)
    }
      });
    }
  }
  final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
  void showSnackBar(String title) {
    final snackbar = SnackBar(content: Text(
      title, textAlign: TextAlign.center, style: TextStyle(fontSize: 15),
    ),);
    scaffoldKey.currentState?.showSnackBar(snackbar);
  }


  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: widget.scaffoldKey,
      backgroundColor: Colors.white,
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(8.0),
            child: Column(
              children: <Widget>[
                const SizedBox(height: 70,),
                const Image(
                  alignment: Alignment.center,
                  height: 100.0,
                  width: 100.0,
                  image: AssetImage('images/TaxiLogo.webp'),
                ),
                const SizedBox(height: 40,),
                const Text('Sign In as a Rider',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 25, fontFamily: 'Brand-Regular'),
                ),

                Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Column(
                    children: <Widget>[
                      TextField(
                        controller: widget.emailController,
                        keyboardType: TextInputType.emailAddress,
                        decoration: const InputDecoration(
                            labelText: 'Email address',
                            labelStyle: TextStyle(
                              fontSize: 14.0,
                            ),
                            hintStyle: TextStyle(
                              color: Colors.grey,
                              fontSize: 10.0,
                            )
                        ),
                        style: const TextStyle(fontSize: 14),
                      ),

                      const SizedBox(height: 10,),

                      TextField(
                        controller: widget.passwordController,
                        obscureText: true,
                        decoration: const InputDecoration(
                            labelText: 'Password',
                            labelStyle: TextStyle(
                              fontSize: 14.0,
                            ),
                            hintStyle: TextStyle(
                              color: Colors.grey,
                              fontSize: 10.0,
                            )
                        ),
                        style: TextStyle(fontSize: 14),
                      ),

                      const SizedBox(height: 40,),

                      TaxiButton(
                          brand: Colors.redAccent,
                          title: 'Login',
                          onPressed: () async {
                            var connectivityResult = await Connectivity().checkConnectivity();
                            if(connectivityResult != ConnectivityResult.mobile && connectivityResult != ConnectivityResult.wifi){
                              widget.showSnackBar('No Internet Connectivity');
                              return;
                            }
                            if(!widget.emailController.text.contains('@')){
                              widget.showSnackBar('Please Enter a valid email Address!');
                              return;
                            }
                            if(widget.passwordController.text.length < 8 ){
                              widget.showSnackBar('Please enter a valid password');
                              return;
                            }
                            widget.login(context);
                          }
                          ),
                    ],
                  ),
                ),

                FlatButton(
                    onPressed: (){
                      Navigator.pushNamedAndRemoveUntil(context, RegistrationPage.id, (route) => false);
                    },
                    child: Text('Don\'t have an account, sign up here')),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

And this is my main.dart file:

import 'package:flutter/material.dart';
import 'package:untitled/Screens/loginpage.dart';
import 'package:untitled/Screens/mainpage.dart';
import 'package:flutter/widgets.dart';
import 'dart:io';

import 'package:untitled/Screens/registrationpage.dart';



Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final FirebaseApp app = await FirebaseApp.configure(
    name: 'db2',
    options: Platform.isIOS
        ? const FirebaseOptions(
      googleAppID: '1:102830:ios:eb23',
      gcmSenderID: '102830',
      databaseURL: 'https://geetaxi',
    )
        : const FirebaseOptions(
      googleAppID: '1:1:android:7ae54d14154e758eee4804',
      apiKey: 'AI',
      databaseURL: 'https://geetaxi',
    ),
  );
  runApp(MyApp());
}


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        fontFamily: 'Brand-Regular',
        primarySwatch: Colors.blue,
      ),
      initialRoute: LoginPage.id,
      routes: {
        RegistrationPage.id:(context) => RegistrationPage(),
        LoginPage.id: (context) => LoginPage(emailController: TextEditingController(), passwordController: TextEditingController(),),
        MainPage.id: (context) => MainPage(),
      },
    );
  }
}

I think there is something wrong with this line and I am not sure if it is correct:

LoginPage.id: (context) => LoginPage(emailController: TextEditingController(), passwordController: TextEditingController(),),

error

CodePudding user response:

The code accesses a collection named: user/...

But by convention users often are stored in a collection named: users/...

This is how to check if a document exists without using a snapshot listener but by using await:

var userRef = await FirebaseFirestore.instance
        .collection("users")
        .doc(user.uid)
        .get();

if (!userRef.exists) {
  // not found
} else {
  print(userRef.data());
}

https://firebase.google.com/docs/firestore/query-data/get-data

  • Related