Flutter向我显示我的loggingInUser为空/无效。但是我在getCurrentUser()方法中保存了用户的值。现在由于这个原因,我的代码在第92行(该行,其后是注释)处得到了异常。例外是-
在处理手势时引发了以下NoSuchMethodError: getter'email'被调用为null。 接收者:null 尝试致电:电子邮件
//但是每当我使用_auth.currentUser.email代替loggingInUser时,我的代码就可以正常运行。我不明白为什么?
请有人帮我,我是新来的。
这是我的聊天屏幕代码-
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:palabrero_chat_app/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ChatScreen extends StatefulWidget {
static const String id = 'chat_screen';
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final myController = TextEditingController();
@override
void dispose() {
myController.dispose();
super.dispose();
}
// ignore: deprecated_member_use
final _firestore = Firestore.instance;
final _auth = FirebaseAuth.instance;
FirebaseUser loggedInUser;
String messageText;
@override
void initState() {
super.initState();
Firebase.initializeApp().whenComplete(() {
print("completed");
setState(() {});
});
getCurrentUser();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if(user!=null) {
loggedInUser = user;
}
}
catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
_auth.signOut();
Navigator.pop(context);
//Implement logout functionality
}),
],
title: Text('⚡️Chat'),
backgroundColor: Colors.lightBlueAccent,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
decoration: kMessageContainerDecoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
onChanged: (value) {
messageText = value;
},
decoration: kMessageTextFieldDecoration,
),
),
FlatButton(
onPressed: () {
getCurrentUser();
//messageText + loggedInUser.email
_firestore.collection('messages').add({
'text' : messageText,
'sender' : loggedInUser.email, //This line no. 92
//If i use _auth.currentUser.email above, in place of loggedInUser, my code
works. Please explain it to me.
});
},
child: Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}
答案 0 :(得分:0)
更改此:
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if(user!=null) {
loggedInUser = user;
}
}
catch (e) {
print(e);
}
}
对此:
void getCurrentUser() {
try {
final user = _auth.currentUser;
if(user!= null) {
setState(() { loggedInUser = user; });
}
}
catch (e) {
print(e);
}
}
由于currentUser
不返回Future
,因此要删除异步/等待状态,也请使用setState
更新变量loggedInUser
答案 1 :(得分:0)
正如Peter所说的..我遵循了他的方法,但是我的代码在我遵循的同时仍然有效:
所以我觉得,这只是针对FirebaseUser,我们需要将setState添加到loggingInUser分配中。
答案 2 :(得分:0)
在函数中
getCurrentUser()
尝试改变 final user = _auth.currentUser;
到final user = _auth.currentUser();
只需添加这些括号。