Home > front end >  Issue with Flutter retrieving data from Firestore (Authenticating different users types from collect
Issue with Flutter retrieving data from Firestore (Authenticating different users types from collect

Time:08-04

I am having an issue with trying to route different users to different views in flutter.

I will attach my code below. I have authentication working and routing to the main view. I am now trying to query a Users table in my database (screenshot attached). I want to check by email that the user isStudent and route to menu page. if not a student then route to a separate page.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_tex/flutter_tex.dart';
import 'package:maths_for_computing/components/roundedButton.dart';
import 'package:maths_for_computing/screens/chat_screen.dart';
import 'package:flutter/material.dart';
import 'package:maths_for_computing/components/roundedButton.dart';
import 'package:maths_for_computing/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:maths_for_computing/screens/latex_example.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'chat_screen.dart';
import 'menu_student.dart';

final GlobalKey<ScaffoldState> _key = GlobalKey(); // Create a key
final _firestore = FirebaseFirestore.instance;

class LoginScreen extends StatefulWidget {
  static const String id = 'login_screen';
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  bool showSpinner = false;
  final _auth = FirebaseAuth.instance;
  late String email;
  late String password;

  Future getUsers(String email) async {
    final users = await _firestore
        .collection('Users')
        .where('email', isEqualTo: email)
        .get();
    for (var user in users.docs) {
      print(user.get("email"));
      //return user.get("isStudent") as String;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Flexible(
                child: Hero(
                  tag: 'logo',
                  child: Container(
                    height: 200.0,
                    child: Image.asset('images/logo.png'),
                  ),
                ),
              ),
              const SizedBox(
                height: 48.0,
              ),
              TextField(
                keyboardType: TextInputType.emailAddress,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  //Do something with the user input.
                  email = value;
                },
                decoration:
                    kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
              ),
              const SizedBox(
                height: 8.0,
              ),
              TextField(
                obscureText: true,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  //Do something with the user input.
                  password = value;
                },
                decoration: kTextFieldDecoration.copyWith(
                    hintText: 'Enter your password'),
              ),
              const SizedBox(
                height: 24.0,
              ),
              RoundedButton(
                title: 'Log In',
                colour: Colors.lightBlueAccent,
                onPressed: () async {
                  setState(() {
                    showSpinner = true;
                  });
                  try {
                    final user = await _auth.signInWithEmailAndPassword(
                        email: email, password: password);

                    String userType = getUsers(email) ;
                    // getUsers(email);
                    if (user != null) {
                      if (isStudent == 'N') {
                        Navigator.pushNamed(context, ChatScreen.id);
                      } else {
                        Navigator.pushNamed(context, MenuScreen.id);
                      }
                    }
                  } catch (e) {
                    print(e);
                  }
                  setState(() {
                    showSpinner = false;
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

enter image description here

Any help or advice on this or best practice would be much appreciated. This is a small app so trying to stay away from Custom claims as I am very new to flutter and don't want to overcomplicate things.

Many thanks E

enter image description here

enter image description here

enter image description here

CodePudding user response:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_tex/flutter_tex.dart';
import 'package:maths_for_computing/components/roundedButton.dart';
import 'package:maths_for_computing/screens/chat_screen.dart';
import 'package:flutter/material.dart';
import 'package:maths_for_computing/components/roundedButton.dart';
import 'package:maths_for_computing/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:maths_for_computing/screens/latex_example.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'chat_screen.dart';
import 'menu_student.dart';

final GlobalKey<ScaffoldState> _key = GlobalKey(); // Create a key
final _firestore = FirebaseFirestore.instance;

class LoginScreen extends StatefulWidget {
  static const String id = 'login_screen';
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  bool showSpinner = false;
  final _auth = FirebaseAuth.instance;
  late String email;
  late String password;

  Future getUsers(String email) async {
    final users = await _firestore
        .collection('Users')
        .where('email', isEqualTo: email)
        .get();
    for (var user in users.docs) {
      print(user.get("email"));
      //return user.get("isStudent") as String;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Flexible(
                child: Hero(
                  tag: 'logo',
                  child: Container(
                    height: 200.0,
                    child: Image.asset('images/logo.png'),
                  ),
                ),
              ),
              const SizedBox(
                height: 48.0,
              ),
              TextField(
                keyboardType: TextInputType.emailAddress,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  //Do something with the user input.
                  email = value;
                },
                decoration:
                kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
              ),
              const SizedBox(
                height: 8.0,
              ),
              TextField(
                obscureText: true,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  //Do something with the user input.
                  password = value;
                },
                decoration: kTextFieldDecoration.copyWith(
                    hintText: 'Enter your password'),
              ),
              const SizedBox(
                height: 24.0,
              ),
              RoundedButton(
                title: 'Log In',
                colour: Colors.lightBlueAccent,
                onPressed: () async {
                  setState(() {
                    showSpinner = true;
                  });
                  try {
                    final _auth = FirebaseAuth.instance;
                    await _auth.signInWithEmailAndPassword(email: email, password: password).then((uid) => {
                      FirebaseFirestore.instance.collection("users").doc(uid.user.uid).get().then((value) {
                        Map<dynamic, dynamic> currentUser = value.data();
                        if(currentUser['isStudent']=="N") {
                          Navigator.pushNamed(context, ChatScreen.id);
                        }
                        else {
                          Navigator.pushNamed(context, MenuScreen.id);
                        }
                      }),
                    });
                  } catch (e) {
                    print(e);
                  }
                  setState(() {
                    showSpinner = false;
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  • Related