我正在开发一个聊天应用程序。我已完成安装Firebase的所有过程,我的应用程序运行正常。但是当我连接Firebase数据库并尝试将消息存储到数据库中时。数据库不会使用新文档(消息和用户电子邮件)进行更新。
这是我的代码-
import 'package:flutter/material.dart';
import 'package:flash_chat/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 _firestore = Firestore.instance;
String messageText;
final _auth = FirebaseAuth.instance;
FirebaseUser loggedinUser;
void getCurrentUser() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedinUser = user;
print(user.email);
}
} 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;
//Do something with the user input.
},
decoration: kMessageTextFieldDecoration,
),
),
FlatButton(
onPressed: () {
_firestore.collection('messages').add({
'sender': loggedinUser.email,
'text': messageText,
});
//Implement send functionality.
},
child: Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}
**
答案 0 :(得分:1)
问题似乎出在您试图添加具有null
值的数据,这就是为什么您看不到任何更改的原因。
看似null
的值是loggedinUser.email
和messageText
,请检查用户是否具有email
,并在{{ 1}}应该在messageText
内执行onChanged
,但是您可以在messageText = value;
上添加setState()
,然后使用controller
。 / p>