简体   繁体   English

Flutter 用户认证

[英]Flutter User Auth

I'm new to flutter hence I need some help.我是 flutter 的新手,因此我需要一些帮助。 I use the phone authentication method to log in a user.我使用电话验证方法登录用户。 Now when the user is successfully logged in I receive the following error:现在,当用户成功登录时,我收到以下错误:

在此处输入图像描述

Here's my full code:这是我的完整代码:

import 'package:flutter/material.dart';
import 'package:neuroequlibrium/reusable.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class EditDetails extends StatefulWidget {
  @override
  _EditDetailsState createState() => _EditDetailsState();
}

class _EditDetailsState extends State<EditDetails> {
  final _firestore = Firestore.instance;
  final _auth = FirebaseAuth.instance;
  FirebaseUser loggedInUser;

  void getCurrentUser() async {
    final user = await _auth.currentUser();
    try {
      if (user != null) {
        loggedInUser = user;
        print(loggedInUser.phoneNumber);
      }
    } catch (e) {
      print(e);
    }
  }

  void initState() {
    // TODO: implement initState
    super.initState();

    getCurrentUser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Verify your details'),
      ),
      body: Center(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 50.0),
          child: Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 0,
              vertical: 50.0,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                TextLabel('Name'),
                TextField(
                  onChanged: (value) {},
                  decoration: kInputStyle.copyWith(
                    hintText: 'Samyak',
                  ),
                ),
                SizedBox(height: 25.0),
                TextLabel('Date of birth'),
                TextField(
                  onChanged: (value) {},
                  decoration: kInputStyle.copyWith(hintText: '5/10/2003'),
                ),
                SizedBox(height: 25.0),
                TextLabel('Sex'),
                TextField(
                  onChanged: (value) {},
                  decoration: kInputStyle.copyWith(hintText: 'Male'),
                ),
                SizedBox(height: 25.0),
                TextLabel('Phone No.'),
                TextField(
                  onChanged: (value) {},
                  decoration:
                      kInputStyle.copyWith(hintText: loggedInUser.phoneNumber),
                ),
                SizedBox(height: 30.0),
                RoundedButton(
                  color: Colors.blueAccent,
                  text: 'Verify',
                  onPressed: () {
                    // Update Details & Redirect user
                    Navigator.pushNamed(context, 'additional_details1');
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

When I run getCurrentUser() in initState() function I don't get any errors and the user's number is printed in the console.当我在 initState() function 中运行 getCurrentUser() 时,我没有收到任何错误,并且用户的号码会打印在控制台中。 How when I want to display it as a placeholder in one of the text fields the above exception is raised.当我想在其中一个文本字段中将其显示为占位符时,如何引发上述异常。

Also, as I hot reload my app, it starts working perfectly, and the number shows up in the text field without any changes to the code.此外,当我热重新加载我的应用程序时,它开始完美运行,并且数字显示在文本字段中,无需对代码进行任何更改。

Note: I'm using flutter and android studio for development注意:我使用 flutter 和 android studio 进行开发

Any help would be much appreciated!任何帮助将非常感激!

The reason this is happening is because when Flutter builds the widget, first it builds the state of the widget, in that state you're trying to get the user's number BUT you're fetching the numbers only after you're building the widget - hence the error.发生这种情况的原因是因为当 Flutter 构建小部件时,首先它构建小部件的 state,在那个 state 中,你试图在你试图获取用户的号码之后获取用户的号码因此错误。 When you hot reload flutter remembers the variables' data and that's why it is able to update the UI.当你热重载 flutter 会记住变量的数据,这就是它能够更新 UI 的原因。 2 fixes can be made in order to fix this issue:为了解决此问题,可以进行 2 个修复:

(1) - is to first call the getCurrentUser() and only then building the widget super.initState . (1) - 是首先调用getCurrentUser() ,然后才构建小部件super.initState

(2) - when building the object check the data of the variable and if it's null present a different widget. (2) - 在构建 object 时检查变量的数据,如果它是 null,则显示不同的小部件。 when getCurrentUser() is finished update the state of the widget using setState((){})getCurrentUser()完成时,使用setState((){})更新小部件的 state

A simple way to check the variable is using the ?检查变量的一种简单方法是使用? format like so:格式如下:

  int a = 5;
  a == 5 ? print('yes') : print('no');

output is obviously yes output 显然yes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM