Войти два разных типа пользователей - PullRequest
0 голосов
/ 12 марта 2020

Я разрабатываю приложение для домашнего обучения с использованием Flutter и Firebase, но у меня возникла проблема на экране входа в систему, так как я хочу отправить учителя и ученика на разные экраны профиля, но я не могу создать хорошую логи c для этого. Я попытался назначить строку, которая будет сравниваться, чтобы отправить каждого пользователя на соответствующие экраны, но это не сработало, так как предоставляет мне либо ноль. Вот код моего экрана входа в систему.

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:etutor/Animation/FadeAnimation.dart';
import 'package:etutor/ReusableMaterial/BackArrow.dart';
import 'package:etutor/ReusableMaterial/Constants.dart';
import 'package:etutor/ReusableMaterial/Loading.dart';
import 'package:etutor/ReusableMaterial/ReusableButton.dart';
import 'package:etutor/ReusableMaterial/ReusableCard.dart';
import 'package:etutor/Screens/Index.dart';
import 'package:etutor/Screens/ProfileSelection.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class SignIn extends StatefulWidget {
  @override
  _SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final Firestore _firestore = Firestore.instance;

  String email;
  String password;
  bool pass1 = true;
  String userType;
  String loggedInUserID;
  bool loading = false;

  void showErrorMessage(String title, String description) {
    AwesomeDialog(
      context: context,
      dialogType: DialogType.ERROR,
      animType: AnimType.BOTTOMSLIDE,
      tittle: title,
      desc: description,
    ).show();
  }

  Future getUserType() async {
    userType = (await _firestore
        .collection('userData')
        .document(loggedInUserID)
        .get()) as String;
    print(userType);
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
            backgroundColor: kBackgroundColor,
            body: SafeArea(
              child: ListView(
                children: <Widget>[
                  SizedBox(height: 35),
                  FadeAnimation(
                    0.5,
                    Center(
                      child: Text(
                        'Sign In',
                        style: kHeadingStyle,
                      ),
                    ),
                  ),
                  BackArrow(),
                  SizedBox(
                    height: 15,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      FadeAnimation(
                        0.5,
                        Text(
                          'Enter your details to access your Account.',
                          style: kTextLineStyle,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 45),
                  Padding(
                    padding: const EdgeInsets.only(left: 30, right: 30),
                    child: FadeAnimation(
                      0.5,
                      Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                color: Color.fromRGBO(84, 104, 255, .3),
                                blurRadius: 20,
                                offset: Offset(0, 10),
                              )
                            ]),
                        child: Column(
                          children: <Widget>[
                            ReusableCard(
                              onChanged: (value) {
                                email = value;
                              },
                              hintLabel: 'Email',
                            ),
                            ReusablePasswordCard(
                              onChanged: (value) {
                                password = value;
                              },
                              hintLabel: 'Password',
                              pass: pass1,
                              onPress: () {
                                setState(() {
                                  pass1 = !pass1;
                                });
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Row(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(left: 28),
                      ),
                      FadeAnimation(
                        0.5,
                        FlatButton(
                          child: Text(
                            'Forgot Password ?',
                            style: TextStyle(
                              fontFamily: 'Roboto',
                              fontSize: 15,
                              color: kBlueColor,
                            ),
                          ),
                          onPressed: () {},
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 30,
                  ),
                  FadeAnimation(
                    0.5,
                    Center(
                      child: Text(
                        'Don\'t have an Account ?',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF546270),
                        ),
                      ),
                    ),
                  ),
                  FadeAnimation(
                    0.5,
                    Center(
                      child: FlatButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => ProfileSelection(),
                            ),
                          );
                        },
                        child: Text(
                          'SIGN UP',
                          style: TextStyle(
                            color: kBlueColor,
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  FadeAnimation(
                    0.5,
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        ReusableButton(
                          label: 'Continue',
                          onPress: () async {
                            if (!email.contains('@') ||
                                email == null ||
                                !email.contains('.com')) {
                              showErrorMessage('Invalid Email',
                                  'The email you entered is wrong, please check your email format and try again');
                            } else if (password == null) {
                              showErrorMessage('Invalid Password',
                                  'The password field is empty');
                            } else {
                              try {
                                setState(() {
                                  loading = true;
                                });

                                FirebaseUser signedInUser =
                                    (await _auth.signInWithEmailAndPassword(
                                            email: email, password: password))
                                        .user;
                                if (!signedInUser.isEmailVerified) {
                                  setState(() {
                                    loading = false;
                                  });
                                  AwesomeDialog(
                                          context: context,
                                          dialogType: DialogType.ERROR,
                                          animType: AnimType.BOTTOMSLIDE,
                                          tittle: 'Error!',
                                          desc:
                                              'Your email has not been verified please verify your email first')
                                      .show();
                                } else {
                                  if (signedInUser != null) {
                                    setState(() {
                                      loggedInUserID = signedInUser.uid;
//                                      print(loggedInUserID);
                                    });
                                  }

                                  while (loggedInUserID == null) {}
                                  if (loggedInUserID != null) {
                                    getUserType();
                                    setState(() {
                                      loading = false;
                                    });
                                    print(loggedInUserID);
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) =>
                                            Index(loggedInUserID),
                                      ),
                                    );
                                  }
                                }
                              } catch (e) {
                                print(e);
                                showErrorMessage('Error', e);
                              }
                            }
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
  }
}

1 Ответ

0 голосов
/ 12 марта 2020

Возвращает ноль, потому что ваша функция getUserType() является асинхронной c, и когда вы проверяете тип пользователя, он не ждет, пока ваша функция завершит работу и вернет данные.

Вы должны ждать данных чтобы быть найденным на пути, используя это await

if (loggedInUserID != null) {
    await getUserType();
    setState(() {
    loading = false;
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...