如何在登录/注册后消失加载屏幕? (颤振/飞镖)

时间:2021-01-05 11:39:35

标签: firebase flutter dart google-cloud-firestore

当用户第一次启动我的应用时,他可以在注册表单和登录表单之间切换。完成其中一个表单后,他应该会看到加载屏幕,直到创建或登录用户。不幸的是,在我的情况下,尽管创建了用户,但加载屏幕并没有消失。 我该如何解决这个问题?

登录表单:

class SignIn extends StatefulWidget {
  final Function toggleView;
  SignIn({this.toggleView});

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

class _SignInState extends State<SignIn> {
  final AuthService _auth = AuthService();
  final _formKey = GlobalKey<FormState>();
  bool loading = false;

  // text field state
  String email = '';
  String password = '';
  String error = '';

  static const color = const Color(0xFF2F80ED);

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
            backgroundColor: Colors.white,
            resizeToAvoidBottomInset: false,
            body: Stack(
              children: <Widget>[
                Container(
                  child: Positioned(
                    top: 0,
                    right: 0,
                    child: Image.asset(
                      'assets/canvas-1-ws.png',
                    ),
                  ),
                ),
                Positioned(
                  top: 25.0,
                  left: 5.0,
                  child: IconButton(
                    icon: Icon(
                      Icons.close,
                      color: Colors.black,
                      size: 35.0,
                    ),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => Welcome(),
                        ),
                      );
                    },
                  ),
                ),
                Container(
                  child: Positioned(
                    bottom: 0,
                    left: 0,
                    child: Image.asset(
                      'assets/canvas-2-ws.png',
                    ),
                  ),
                ),
                Center(
                  child: Stack(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(
                          left: 50.0,
                          right: 50.0,
                        ),
                        child: Container(
                          child: Form(
                            key: _formKey,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Text(
                                  'Login',
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontFamily: 'Roboto Black',
                                    fontSize: 35.0,
                                  ),
                                ),
                                SizedBox(
                                  height: 30.0,
                                ),
                                TextFormField(
                                  style: TextStyle(
                                    fontFamily: 'Roboto Light',
                                    color: Colors.black,
                                  ),
                                  cursorColor: Colors.black,
                                  decoration: InputDecoration(
                                    fillColor: Colors.black,
                                    hintText: 'Email',
                                    hintStyle: TextStyle(
                                      fontFamily: 'Roboto Light',
                                      color: Colors.black,
                                    ),
                                    enabledBorder: UnderlineInputBorder(
                                      borderSide: BorderSide(
                                        color: Colors.black,
                                        width: 1.0,
                                      ),
                                    ),
                                    focusedBorder: UnderlineInputBorder(
                                      borderSide: BorderSide(
                                        color: Colors.black,
                                        width: 1.0,
                                      ),
                                    ),
                                  ),
                                  validator: (val) => val.isEmpty
                                      ? 'Bitte gültige Email'
                                      : null,
                                  onChanged: (val) {
                                    setState(() => email = val);
                                  },
                                ),
                                SizedBox(
                                  height: 20.0,
                                ),
                                TextFormField(
                                    style: TextStyle(
                                      fontFamily: 'Roboto Light',
                                      color: Colors.black,
                                    ),
                                    cursorColor: Colors.black,
                                    decoration: InputDecoration(
                                      fillColor: Colors.black,
                                      hintText: 'Passwort',
                                      hintStyle: TextStyle(
                                        fontFamily: 'Roboto Light',
                                        color: Colors.black,
                                      ),
                                      enabledBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                          color: Colors.black,
                                          width: 1.0,
                                        ),
                                      ),
                                      focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                          color: Colors.black,
                                          width: 1.0,
                                        ),
                                      ),
                                    ),
                                    obscureText: true,
                                    validator: (val) => val.isEmpty
                                        ? 'Bitte gültiges Passwort'
                                        : null,
                                    onChanged: (val) {
                                      setState(() => password = val);
                                    }),
                                SizedBox(
                                  height: 45.0,
                                ),
                                ButtonTheme(
                                  minWidth: 200,
                                  height: 50,
                                  child: RaisedButton(
                                    elevation: 0,
                                    color: color,
                                    textColor: Colors.white,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(30.0),
                                      side: BorderSide(color: color),
                                    ),
                                    child: Container(
                                      decoration: BoxDecoration(
                                        boxShadow: [
                                          BoxShadow(
                                            color: color,
                                            spreadRadius: 10.0,
                                            blurRadius: 20.0,
                                            offset: Offset(0, 3),
                                          ),
                                        ],
                                      ),
                                      child: Text(
                                        'Login',
                                        style: TextStyle(
                                            fontFamily: 'Roboto Light',
                                            fontSize: 25.0),
                                      ),
                                    ),
                                    onPressed: () async {
                                      if (_formKey.currentState.validate()) {
                                        setState(() => loading = true);
                                        dynamic result = await _auth
                                            .signInWithEmailAndPassword(
                                                email, password);
                                        if (result == null) {
                                          setState(() {
                                            error = 'Falsche Email/Password';
                                            loading = false;
                                          });
                                        }
                                      }
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
  }
}

注册表格几乎相似...

文件,用户可以在其中切换表单:

class Welcome extends StatefulWidget {
  final Function toggleView;
  Welcome({this.toggleView});

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

class _WelcomeState extends State<Welcome> {
  static const color = const Color(0xFF2F80ED);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: <Widget>[
          Positioned(
            top: 0,
            right: 0,
            child: Image.asset('assets/canvas-1-ws.png'),
          ),
          Positioned(
            bottom: 0,
            left: 0,
            child: Image.asset('assets/canvas-2-ws.png'),
          ),
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  'assets/Skiclublogo_transparent.png',
                  scale: 4,
                ),
                SizedBox(
                  height: 40.0,
                ),
                ButtonTheme(
                  minWidth: 200,
                  height: 50,
                  child: RaisedButton(
                      elevation: 0,
                      color: color,
                      textColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.0),
                        side: BorderSide(color: color),
                      ),
                      child: Container(
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: color,
                              spreadRadius: 10.0,
                              blurRadius: 20.0,
                              offset: Offset(0, 3),
                            ),
                          ],
                        ),
                        child: Text(
                          'Registrieren',
                          style: TextStyle(
                              fontFamily: 'Roboto Light', fontSize: 25.0),
                        ),
                      ),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => Register(),
                          ),
                        );
                      }),
                ),
                SizedBox(
                  height: 40.0,
                ),
                ButtonTheme(
                  minWidth: 200,
                  height: 50,
                  child: RaisedButton(
                      elevation: 0,
                      color: color,
                      textColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.0),
                        side: BorderSide(color: color),
                      ),
                      child: Container(
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: color,
                              spreadRadius: 10.0,
                              blurRadius: 20.0,
                              offset: Offset(0, 3),
                            ),
                          ],
                        ),
                        child: Text(
                          'Login',
                          style: TextStyle(
                              fontFamily: 'Roboto Light', fontSize: 25.0),
                        ),
                      ),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => SignIn(),
                          ),
                        );
                      }),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

auth 文件,用户在其中创建或登录:

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // create user obj based on FirrebaseUser
  User _userFromFirebaseUser(FirebaseUser user) {
    return user != null ? User(uid: user.uid) : null;
  }

  // auth change user stream
  Stream<User> get user {
    return _auth.onAuthStateChanged.map(_userFromFirebaseUser);
  }

  // sign in anonmously
  Future signInAnon() async {
    try {
      AuthResult result = await _auth.signInAnonymously();
      FirebaseUser user = result.user;

      // create a new document for the user with the uid
      await DatabaseService(uid: user.uid).updateUserData(
          user.displayName, user.email, user.photoUrl, user.uid);
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // sign in email & password
  Future signInWithEmailAndPassword(String email, String password) async {
    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(
          email: email, password: password);
      FirebaseUser user = result.user;
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // register with email & password
  Future registerWithEmailAndPassword(
      String email, String password, String name) async {
    try {
      AuthResult result = await _auth.createUserWithEmailAndPassword(
          email: email, password: password);
      FirebaseUser user = result.user;

      // update user info
      UserUpdateInfo userUpdateInfo = UserUpdateInfo();
      userUpdateInfo.displayName = name;
      await user.updateProfile(userUpdateInfo);
      await user.reload();
      user = await FirebaseAuth.instance.currentUser();

      // create a new document for the user with the uid
      await DatabaseService(uid: user.uid).updateUserData(
          user.displayName, user.email, user.photoUrl, user.uid);
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // current user
  void inputData() async {
    final FirebaseUser user = await _auth.currentUser();
    final uid = user.uid;
    // here you write the codes to input the data into firestore
  }
}

包装文件,应用程序在其中检查用户是否是新用户:

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    print(user);

    // return either Home or Authenticate widget
    if (user == null) {
      return Welcome();
    } else {
      return DrawerNav();
    }
  }
}

载入画面文件:

class Loading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Center(
        child: SpinKitWave(
          color: Colors.black,
          size: 50.0,
        ),
      ),
    );
  }
}

非常感谢您阅读所有内容!

2 个答案:

答案 0 :(得分:1)

您并不总是在创建用户后调用 setState。

这会起作用

                      onPressed: (){ if (_formKey.currentState.validate()) {
                                    setState(() => loading = true);
                                    dynamic result = await _auth
                                        .signInWithEmailAndPassword(
                                            email, password);
                                    setState(() => loading = false);
                                    if (result == null) {
                                      setState(() {
                                        error = 'Falsche Email/Password';
                                      });
                                    }
                                  }},

答案 1 :(得分:0)

我向你解释我的朋友

设置一个名为 loading 的 #include <iostream> int main() { usmall foo = 3; usmall bar = 30; usmall baz = foo * bar; std::cout << static_cast<unsigned>(baz) << '\n'; // prints 25 } 变量

boolean

if loading = false; is loading display loading screen else 显示你的表单 ui 使用 true

在创建用户时更改ternary operator的{​​{1}},以便加载屏幕出现

state

在创建用户后,再次将loading的{​​{1}}更改为 setState(() { loading=true; });

state

这是 loading false

中的模板
 setState(() { loading=false; });