[英]Flutter User Auth
我是 flutter 的新手,因此我需要一些幫助。 我使用電話驗證方法登錄用戶。 現在,當用戶成功登錄時,我收到以下錯誤:
這是我的完整代碼:
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');
},
),
],
),
),
),
),
);
}
}
當我在 initState() function 中運行 getCurrentUser() 時,我沒有收到任何錯誤,並且用戶的號碼會打印在控制台中。 當我想在其中一個文本字段中將其顯示為占位符時,如何引發上述異常。
此外,當我熱重新加載我的應用程序時,它開始完美運行,並且數字顯示在文本字段中,無需對代碼進行任何更改。
注意:我使用 flutter 和 android studio 進行開發
任何幫助將非常感激!
發生這種情況的原因是因為當 Flutter 構建小部件時,首先它構建小部件的 state,在那個 state 中,你試圖在你試圖獲取用戶的號碼之后獲取用戶的號碼因此錯誤。 當你熱重載 flutter 會記住變量的數據,這就是它能夠更新 UI 的原因。 為了解決此問題,可以進行 2 個修復:
(1) - 是首先調用getCurrentUser()
,然后才構建小部件super.initState
。
(2) - 在構建 object 時檢查變量的數據,如果它是 null,則顯示不同的小部件。 當getCurrentUser()
完成時,使用setState((){})
更新小部件的 state
檢查變量的一種簡單方法是使用?
格式如下:
int a = 5;
a == 5 ? print('yes') : print('no');
output 顯然yes
的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.