I am working on a chatting app. I have done all the processes to install firebase and my app is working fine. But when I connected the firebase database and tried to store the messages into the database. The database does not update with the new document(message and user email).
This is my code -
this is how my firebase database page looks like
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,
),
),
],
),
),
],
),
),
);
}
}
**
It seems that the problem is you're trying to add data with null
values, and that's why you don't see any changes.
The values that seems to be null
are loggedinUser.email
and messageText
, check if the user has an email
and for the messageText
, in onChanged
you should do messageText = value;
inside a setState()
, but instead of doing that you could add a controller
to the TextField
and then use controller.text
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.