why is my user detail not saving into realtime database? - firebase

I am developing a flutter web app. The code for sign-in and login works fine but the data are not saving into my real-time database. This code works fine for the android app and saving user details on firebase. What is wrong with it?
email_signin.dart
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:new_project/UserHome.dart';
class EmailSignUp extends StatefulWidget {
#override
_EmailSignUpState createState() => _EmailSignUpState();
}
class _EmailSignUpState extends State<EmailSignUp> {
bool isLoading = false;
final _formKey = GlobalKey<FormState>();
FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final firestoreInstance = FirebaseFirestore.instance;
DatabaseReference dbRef =
FirebaseDatabase.instance.reference().child("Users");
TextEditingController emailController = TextEditingController();
TextEditingController nameController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController ageController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Sign Up")),
body: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: nameController,
decoration: InputDecoration(
labelText: "Enter User Name",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter User Name';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: emailController,
decoration: InputDecoration(
labelText: "Enter Email",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter an Email Address';
} else if (!value.contains('#')) {
return 'Please enter a valid email address';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: ageController,
decoration: InputDecoration(
labelText: "Enter Age",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter Age';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
obscureText: true,
controller: passwordController,
decoration: InputDecoration(
labelText: "Enter Password",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter Password';
} else if (value.length < 6) {
return 'Password must be atleast 6 characters!';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: isLoading
? CircularProgressIndicator()
: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
Colors.lightBlue)),
onPressed: () {
if (_formKey.currentState.validate()) {
setState(() {
isLoading = false;
});
registerToFb();
}
},
child: Text('Submit'),
),
)
]))));
}
void registerToFb() {
firebaseAuth
.createUserWithEmailAndPassword(
email: emailController.text, password: passwordController.text)
.then((result) {
dbRef.child(result.user.uid).set({
"email": emailController.text,
"age": ageController.text,
"name": nameController.text
}).then((res) {
isLoading = false;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => UserHome(uid: result.user.uid)),
);
});
}).catchError((err) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text(err.message),
actions: [
TextButton(
child: Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
});
}
#override
void dispose() {
super.dispose();
nameController.dispose();
emailController.dispose();
passwordController.dispose();
ageController.dispose();
}
}
class FirebaseFirestore {
static var instance;
}
email_login.dart
import 'package:flutter/material.dart';
import 'package:new_project/UserHome.dart';
class EmailLogIn extends StatefulWidget {
#override
_EmailLogInState createState() => _EmailLogInState();
}
class _EmailLogInState extends State<EmailLogIn> {
final _formKey = GlobalKey<FormState>();
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
bool isLoading = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Login")),
body: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: emailController,
decoration: InputDecoration(
labelText: "Enter Email Address",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter Email Address';
} else if (!value.contains('#')) {
return 'Please enter a valid email address!';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
obscureText: true,
controller: passwordController,
decoration: InputDecoration(
labelText: "Enter Password",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Enter Password';
} else if (value.length < 6) {
return 'Password must be atleast 6 characters!';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: isLoading
? CircularProgressIndicator()
: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
Colors.lightBlue)),
onPressed: () {
if (_formKey.currentState.validate()) {
setState(() {
isLoading = true;
});
logInToFb();
}
},
child: Text('Submit'),
),
)
]))));
}
void logInToFb() {
FirebaseAuth.instance
.signInWithEmailAndPassword(
email: emailController.text, password: passwordController.text)
.then((result) {
isLoading = false;
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => UserHome(uid: result.user.uid)),
);
}).catchError((err) {
print(err.message);
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text(err.message),
actions: [
ElevatedButton(
child: Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
});
}
}
userhomepage.dart
import 'package:flutter/material.dart';
import 'package:new_project/widgets/all_pro.dart';
// ignore: must_be_immutable
class UserHome extends StatefulWidget {
String uid;
String userEmail;
UserHome({this.uid, this.userEmail});
#override
_UserHomeState createState() => _UserHomeState();
}
class _UserHomeState extends State<UserHome> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xffa58faa),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
accountEmail: FutureBuilder(
future: FirebaseDatabase.instance
.reference()
.child("Users")
.child(widget.uid)
.once(),
builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.value['email']);
} else {
return CircularProgressIndicator();
}
}),
accountName: FutureBuilder(
future: FirebaseDatabase.instance
.reference()
.child("Users")
.child(widget.uid)
.once(),
builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.value['name']);
} else {
return CircularProgressIndicator();
}
}),
decoration: BoxDecoration(
color: Color(0xFFf38181),
),
),
ListTile(
leading: new IconButton(
icon: new Icon(Icons.home, color: Colors.black),
onPressed: () => null,
),
title: Text('Home'),
onTap: () {
print(widget.uid);
},
),
ListTile(
leading: new IconButton(
icon: new Icon(Icons.settings, color: Colors.black),
onPressed: () => null,
),
title: Text('Settings'),
onTap: () {
print(widget.uid);
},
),
],
),
),
body: ListView(
children: <Widget>[
Container(height: 300, child: AllProducts()),
],
));
}
}
The authentication works fine but my problem is with the data not going into the realtime database. It is always showing null.

Related

How to Add the displayName While SigningUp using createUserWithEmailAndPassword

I was trying to add the display name to the user immediately after the signup(using createUserWithEmailAndPassword ) and store it in name field in firestore. But when I see it in firestore it says null, I am completely new to this,
Here is how I trying to do it:
UserSignUp.dart
class UserSignUp{
static FirebaseAuth _auth = FirebaseAuth.instance;
static signupWithEmail({String email, String password, String name}) async {
final res = await _auth.createUserWithEmailAndPassword(
email: email, password: password).then(
(value) async {
await FirebaseAuth.instance.currentUser.updateProfile(
displayName: name,
);
},
);
final User user = res.user;
return user;
}
class UserHelper {
static FirebaseFirestore _db = FirebaseFirestore.instance;
static saveUser(User user) async {
Map<String, dynamic> userData = {
"name": user.displayName,
"email": user.email,
"last_login": user.metadata.lastSignInTime.millisecondsSinceEpoch,
"created_at": user.metadata.creationTime.millisecondsSinceEpoch,
"role": "user",
};
final userRef = _db.collection("users").doc(user.uid);
if ((await userRef.get()).exists) {
await userRef.update({
"last_login": user.metadata.lastSignInTime.millisecondsSinceEpoch,
});
} else {
await _db.collection("users").doc(user.uid).set(userData);
}
await _saveDevice(user);
}
}
}
**
Signup_screen.dart
**
class Body extends StatefulWidget {
#override
_SignupPageState createState() => _SignupPageState();
}
class _SignupPageState extends State<Body> {
TextEditingController _emailController;
TextEditingController _passwordController;
TextEditingController _nameController;
#override
void initState() {
super.initState();
_emailController = TextEditingController(text: "");
_passwordController = TextEditingController(text: "");
_nameController = TextEditingController(text: "");
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Background(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"SIGNUP",
style: TextStyle(fontWeight: FontWeight.bold),
),
width: size.width * 0.8,
decoration: BoxDecoration(
color: kPrimaryLightColor,
borderRadius: BorderRadius.circular(29),
),
child: TextField(
controller: _nameController,
// onChanged: (value) {},
cursorColor: kPrimaryColor,
decoration: InputDecoration(
icon: Icon(
Icons.person,
color: kPrimaryColor,
),
hintText: "Full Name",
border: InputBorder.none,
),
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 5),
width: size.width * 0.8,
decoration: BoxDecoration(
color: kPrimaryLightColor,
borderRadius: BorderRadius.circular(29),
),
child: TextField(
controller: _emailController,
// onChanged: (value) {},
cursorColor: kPrimaryColor,
decoration: InputDecoration(
icon: Icon(
Icons.person,
color: kPrimaryColor,
),
hintText: "Your Email",
border: InputBorder.none,
),
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 5),
width: size.width * 0.8,
decoration: BoxDecoration(
color: kPrimaryLightColor,
borderRadius: BorderRadius.circular(29),
),
child: TextField(
controller: _passwordController,
obscureText: true,
// onChanged: (value) {},
cursorColor: kPrimaryColor,
decoration: InputDecoration(
hintText: "Password",
icon: Icon(
Icons.lock,
color: kPrimaryColor,
),
suffixIcon: Icon(
Icons.visibility,
color: kPrimaryColor,
),
border: InputBorder.none,
),
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
width: size.width * 0.8,
child: ClipRRect(
borderRadius: BorderRadius.circular(29),
child: FlatButton(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 40),
color: kPrimaryColor,
onPressed: () async {
if (_emailController.text.isEmpty ||
_passwordController.text.isEmpty) {
print("Email and password cannot be empty");
return;
}
try {
final user = await UserSignUp.signupWithEmail(
email: _emailController.text,
password: _passwordController.text,
name: _nameController.text);
if (user != null) {
print("signup successful");
// Navigator.pop(context);
}
} catch (e) {
print(e);
}
},
child: Text(
"SIGNUP",
style: TextStyle(color: Colors.white),
),
),
),
),
),
),
);
}
}
Main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Auth',
theme: ThemeData(
primaryColor: kPrimaryColor,
scaffoldBackgroundColor: Colors.white,
),
home: MainScreen(),
);
}
}
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder<User>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if(snapshot.hasData && snapshot.data != null) {
UserHelper.saveUser(snapshot.data);
return StreamBuilder<DocumentSnapshot>(
stream: FirebaseFirestore.instance.collection("users").doc(snapshot.data.uid).snapshots() ,
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot){
if(snapshot.hasData && snapshot.data != null) {
final userDoc = snapshot.data;
final user = userDoc.data();
if(user['role'] == 'user') {
return //;
}else{
return //;
}
}else{
return Material(
child: Center(child: CircularProgressIndicator(),),
);
}
},
);
}
return //;
}
);
}
}
but in my firestore the name filled is null
enter image description here
From shared code, I would like to share my understanding and thoughts which might help you to get your solution.
I know, you are already aware about this and that might be the reason you are storing user's info based on section 2's callback event.
Section 1
This part of the code will on save user's name on Firebase Auth only not on Firestore
You can just verify if user's name is updated on firebase auth user's list.
UserSignUp -> signupWithEmail -> currentUser.updateProfile
Section 2
UserHelper.saveUser is called based on authStateChanges not user profile info changes from Firebase.
So, there are higher probability user's display name will be updated on profile info after this callback..
Hence, user's displayName may be null while you are saving data on Firestore.
MainScreen -> StreamBuilder -> UserHelper.saveUser
Suggestion
I would suggest you to save user's info after updating the user's display name on profile to Firestore instead of authStateChanges event.

How to edit firebase existing document with flutter

I try to build a note taking app in flutter, when i try to edit old note i dont see any change,it takes old value.
Thats my collection
My home Page:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:story_note/pages/ajoutNote.dart';
import 'package:story_note/pages/authController.dart';
import 'package:story_note/pages/detailNote.dart';
import 'package:story_note/pages/modifierNote.dart';
import 'package:story_note/pages/modifyNote.dart';
import 'package:timeago/timeago.dart' as timeago;
class Home extends StatefulWidget{
#override
_HomeState createState()=>_HomeState();
}
class _HomeState extends State<Home>{
FirebaseUser currentUser;
String nomUser,emailUser;
Widget _boiteDuDialog(BuildContext, String nom, String email){
return SimpleDialog(
contentPadding: EdgeInsets.zero,
children:<Widget> [
Padding(padding: EdgeInsets.all(8.0),
child: Column(
children:<Widget> [
Text('$nom',style: Theme.of(context).textTheme.title,),
Text('$email',style: Theme.of(context).textTheme.subtitle1,),
SizedBox(height: 10.0,),
Wrap(
children:<Widget> [
FlatButton(color: Colors.red,onPressed:()async{
FirebaseAuth _auth = FirebaseAuth.instance;
await _auth.signOut();
setState(() {
Navigator.pop(context);
});
}, child:Text('Déconnexion')),
FlatButton(onPressed:(){
Navigator.pop(context);
}, child: Text('Annuler'))
],
)
],
),
),
],
);
}
#override
Widget build(BuildContext context) {
// TODO: implement build
final utilisateur = Provider.of<Utilisateur>(context);
FirebaseAuth.instance.currentUser().then((FirebaseUser user){
setState(() {
this.currentUser=user;
});
});
String _idUser(){
if(currentUser!=null){
return currentUser.uid;
}else{
return 'pas id';
}
}
GetCurrentUserData(idUser: utilisateur.idUser).dataUser.forEach((snapshot){
this.nomUser = snapshot.nomComplet;
this.emailUser = snapshot.email;
});
Widget _buildListItem(DocumentSnapshot document){
Firestore.instance.collection('utilisateurs').document(utilisateur.idUser).collection('notes').snapshots();
Timestamp t = document['timestamp'];
final DateTime d = t.toDate();
final DateTime h = DateTime.now();
final diff = d.difference(h).inMinutes;
final date = new DateTime.now().subtract(new Duration(minutes: diff));
String realdate = timeago.format(date);
return Dismissible (
key: new Key(ObjectKey(document.data.keys).toString()),
onDismissed: (direction)async{
await Firestore.instance.collection('utilisateurs').document(utilisateur.idUser).collection('notes').document().delete();
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('${document['titre']} was deleted',style: new TextStyle(color: Colors.red),),
)
);
},
background: new Container(
color: Colors.red,
),
child:Container(
padding: EdgeInsets.symmetric(horizontal: 10),
height: 80,
alignment: Alignment.center,
child:Card(
elevation: 10.0,
color: Theme.of(context).primaryColor,
shadowColor: Colors.white24,
child:new ListTile(
onTap:(){
print('cest fait');
Navigator.push(context, MaterialPageRoute(builder: (context)=>ModifierNote(
titre:document['titre'],
note:document['note']
)));
},
leading: Icon(Icons.mood_rounded,color: Colors.blue,size: 30,),
title: new Text('${document['titre']}',style: new TextStyle(fontSize: 20,fontWeight: FontWeight.bold),textAlign: TextAlign.justify,),
subtitle: new Text('${document['note']}',maxLines: 1,),
trailing: new Text(realdate),
),
)
)
);
}
return Scaffold(
appBar: AppBar(
title: Text('Story Notes',),
centerTitle: true,
backgroundColor: Theme.of(context).primaryColor,
actions: [
IconButton(icon: Icon(Icons.search_rounded), onPressed:(){
}),
IconButton(icon: Icon(Icons.person), onPressed:()=>showDialog(context: context,builder: (context)=>
_boiteDuDialog(context,nomUser,emailUser))),
],
),
body: Padding(
padding: EdgeInsets.only(top: 25),
child:StreamBuilder(
stream: Firestore.instance.collection('utilisateurs').document(utilisateur.idUser).collection('notes').snapshots(),
builder: (context,snapshot){
if(!snapshot.hasData)
return Text('loading....');
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder:(context,index)=>
_buildListItem(snapshot.data.documents[index]),
);
},
),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.blue,
child: Icon(Icons.note_add,),
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=>AjoutNote()));
},
),
);
}
}
my Modification page:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class ModifierNote extends StatefulWidget{
final String titre,note;
ModifierNote({this.titre,this.note});
#override
ModifierNoteState createState()=> ModifierNoteState();
}
class ModifierNoteState extends State<ModifierNote>{
final CollectionReference collectionUser = Firestore.instance.collection('utilisateurs');
FirebaseUser currentUser;
final _formkey = GlobalKey<FormState>();
bool _titreValid = true;
bool _noteValid = true;
#override
Widget build(BuildContext context) {
// TODO: implement build
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() {
this.currentUser = user;
});
});
String _idUser(){
if(currentUser!=null){
return currentUser.uid;
}else{
return 'Pas id';
}
}
String titre1 = widget.titre;
String note1 = widget.note;
final DateTime timestamp = DateTime.now();
modifierNotes()async{
await collectionUser.document(_idUser()).collection('notes')
.document('note')
.setData({
'titre': titre1,
'note': note1,
'timestamp':timestamp
});
this.setState(() {
Navigator.pop(context);
});
}
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
title: Text('Notes'),
actions: [
RaisedButton(
onPressed:()async{
if(_formkey.currentState.validate()){
modifierNotes();
}
},
child:Text('Modifier')
),
],
),
body: Stack(
children: [
SingleChildScrollView(
child:Card(
elevation: 15,
color: Theme.of(context).primaryColor,
child: Form(
key: _formkey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children:<Widget> [
TextFormField(
initialValue: titre1,
decoration: InputDecoration(
labelText: 'Titre',
prefixIcon: Icon(Icons.speaker_notes_sharp),
),
validator: (val) =>
val.isEmpty ? 'Entrez un titre' : null,
onChanged: (val)=>setState(()=>titre1 = val),
),
TextFormField(
initialValue: note1,
keyboardType: TextInputType.multiline,
maxLines: 5000,
autofocus: true,
decoration: InputDecoration(
hintText: 'Comment vous sentez vous ?',
hintStyle: new TextStyle(fontSize: 20),
),
validator: (val) =>
val.isEmpty ? 'Entrez une note' : null,
onChanged: (val)=>setState(()=>note1 = val),
),
],
),
),
),
),
],
),
);
}
}
And Addpage:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class AjoutNote extends StatefulWidget{
AjoutNoteState createState()=> AjoutNoteState();
}
class AjoutNoteState extends State<AjoutNote>{
String titre;
String note;
final _formkey = GlobalKey<FormState>();
final CollectionReference collectionUser = Firestore.instance.collection('utilisateurs');
final DateTime timestamp = DateTime.now();
FirebaseUser currentUser;
#override
Widget build(BuildContext context) {
// TODO: implement build
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() {
this.currentUser = user;
});
});
String _idUser(){
if(currentUser!=null){
return currentUser.uid;
}else{
return 'Pas id';
}
}
enegistrezNote()async{
await collectionUser.document(_idUser()).collection('notes')
.document('note')
.setData({
'titre': titre,
'note': note,
'timestamp':timestamp
});
this.setState(() {
Navigator.pop(context);
});
}
return Scaffold(
backgroundColor: Theme.of(context).primaryColor,
appBar: AppBar(
title: Text('Ajouter une note'),
centerTitle: true,
backgroundColor: Theme.of(context).primaryColor,
actions: [
RaisedButton(onPressed:(){
if(_formkey.currentState.validate()){
enegistrezNote();
}
},
child: Text("Enregistrez"),
),
],
),
body: new Container(
child:SingleChildScrollView(
child: Card(
elevation: 15,
color: Theme.of(context).primaryColor,
child: Form(
key: _formkey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children:<Widget> [
TextFormField(
decoration: InputDecoration(
labelText: 'Titre',
prefixIcon: Icon(Icons.speaker_notes_sharp)
),
onChanged: (val)=>titre=val,
),
TextFormField(
keyboardType: TextInputType.multiline,
maxLines: 5000,
autofocus: true,
decoration: InputDecoration(
hintText: 'Comment vous sentez vous ?',
hintStyle: new TextStyle(fontSize: 20),
),
onChanged: (val)=>note=val,
)
],
),
),
),
),
),
resizeToAvoidBottomPadding: true,
);
}
}
When i try to modify i dont see any changes.
use update Method in place of set, I have made changes for you:
modifierNotes()async{
await collectionUser.document(_idUser()).collection('notes')
.document('note')
.update({
'titre': titre1,
'note': note1,
'timestamp':timestamp
});
this.setState(() {
Navigator.pop(context);
});
}

Different content for different user Flutter

I've been building an app where users can make a reservation for cat grooming. I already connected the app to Firebase where users can register and log in to the app. Here is the problem, every time I log in with different user account, the reservation history from the other users still there.
How can I make different content for different users that login? so each user can have their own content.
Here is the code from history page.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class HistoryPage extends StatefulWidget {
static const String id = 'HistoryPage';
#override
_HistoryPageState createState() => _HistoryPageState();
}
class _HistoryPageState extends State<HistoryPage> {
final _firestore = Firestore.instance;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.fromLTRB(25.0, 68.0, 70.0, 25.0),
child: Text(
'History',
style: TextStyle(fontSize: 35.0),
),
),
Column(
children: <Widget>[
StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('ReservationData').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
final messages = snapshot.data.documents;
List<HistoryBox> historyWidgets = [];
for (var message in messages) {
final historyDate = message.data['Reservation Date'];
final historyTime = message.data['Reservation Time'];
final historyWidget =
HistoryBox(date: historyDate, time: historyTime);
historyWidgets.add(historyWidget);
}
return Column(
children: historyWidgets,
);
},
),
],
)
],
)),
);
}
}
class HistoryBox extends StatelessWidget {
final String date;
final String time;
HistoryBox({this.date, this.time});
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Material(
elevation: 5.0,
child: Container(
child: Text(
'Date Reservation : \n $date and $time',
style: TextStyle(
fontSize: 20.0,
),
),
),
),
);
}
}
(Updated)
This is the code for users to sign up.
import 'package:flutter/material.dart';
import 'package:project_pi/screens/HomePage/home_page.dart';
import 'inputform_signup.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class SignUpPage extends StatefulWidget {
static const String id = 'SignUpPage';
#override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
final _firestore = Firestore.instance;
final _auth = FirebaseAuth.instance;
bool showSpinner = false;
String nama;
String email;
String password;
String phoneNumber;
#override
Widget build(BuildContext context) {
return Scaffold(
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Form(
child: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'SIGN UP',
style: TextStyle(
fontSize: 28.0,
),
),
InputForm(
hint: 'Full Name',
hidetext: false,
onChanged: (value) {
nama = value;
},
),
InputForm(
hint: 'Email Address',
hidetext: false,
onChanged: (value) {
email = value;
},
),
InputForm(
hint: 'Phone Number',
hidetext: false,
onChanged: (value) {
phoneNumber = value;
},
),
InputForm(
hint: 'Password',
hidetext: true,
onChanged: (value) {
password = value;
},
),
InputForm(
hint: 'Confirm Password',
hidetext: true,
),
SizedBox(height: 15.0),
Container(
height: 45.0,
width: 270.0,
child: RaisedButton(
child: Text('SIGN UP'),
onPressed: () async {
setState(() {
showSpinner = true;
});
try {
final newUser =
await _auth.createUserWithEmailAndPassword(
email: email, password: password);
_firestore.collection('UserAccount').add({
'Email Address': email,
'Full Name': nama,
'Phone Number': phoneNumber,
});
if (newUser != null) {
Navigator.pushNamed(context, HomePage.id);
}
setState(() {
showSpinner = false;
});
} catch (e) {
print(e);
}
},
),
),
SizedBox(
height: 15.0,
),
Text('Have an Account?'),
SizedBox(
height: 7.5,
),
InkWell(
child: Text(
'SIGN IN',
style: TextStyle(
color: Colors.red,
),
),
onTap: () {
AlertDialog(
title: Text("Finish?"),
content: Text("Are you sure with the data?"),
actions: <Widget>[
FlatButton(onPressed: null, child: null)
],
);
},
),
],
),
),
),
),
),
),
);
}
}
And this is the class for the current user that logged in
import 'package:flutter/material.dart';
import 'package:project_pi/screens/HomePage/homebutton.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:project_pi/screens/LiveMaps/live_maps.dart';
import 'package:project_pi/screens/LoginPage/HalamanLogin.dart';
import 'package:project_pi/screens/ReservationHistory/history_page.dart';
import 'package:project_pi/screens/ReservationPage/information_detail.dart';
class HomePage extends StatefulWidget {
static const String id = "HomePage";
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _auth = FirebaseAuth.instance;
FirebaseUser loggedInUser;
#override
void initState() {
super.initState();
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(
body: SafeArea(
child: Expanded(
child: Container(
child: Column(
children: <Widget>[
Container(
margin: EdgeInsets.fromLTRB(25.0, 68.0, 256.0, 47.0),
child: Text(
'Home',
style: TextStyle(fontSize: 35.0),
),
),
Center(
child: Column(
children: <Widget>[
HomeNavButton(
prefixIcon: Icons.date_range,
textbutton: 'Make Reservation',
onPressed: () {
Navigator.pushNamed(context, InformationDetail.id);
},
),
SizedBox(
height: 40.0,
),
HomeNavButton(
prefixIcon: Icons.list,
textbutton: 'Reservation History',
onPressed: () {
Navigator.pushNamed(context, HistoryPage.id);
},
),
SizedBox(
height: 40.0,
),
HomeNavButton(
prefixIcon: Icons.gps_fixed,
textbutton: 'Live Maps Track',
onPressed: () {
Navigator.pushNamed(context, LiveMaps.id);
},
),
SizedBox(
height: 40.0,
),
HomeNavButton(
prefixIcon: Icons.person,
textbutton: 'Account Profile',
onPressed: () {
FirebaseAuth.instance.signOut();
Navigator.pushNamed(context, HalamanLogin.id);
},
),
],
),
),
],
),
),
),
),
);
}
}
how to implement the filter for each current user that logged in so it can show the content based on users?
when user creates an account via firebase they get assigned a uid userId which can be obtained by
String userId;
getCurrentUser() async {
FirebaseUser firebaseUser = await FirebaseAuth.instance.currentUser();
setState(() {
userId = firebaseUser.uid;
});
}
and then while saving reservations you can include a field "userId":userid
now when you query you can query for your currentUser
_firestore.collection('ReservationData') .where("userId", isEqualTo: userId).snapshots(),

Flutter Login with firebase return ERROR_INVALID_EMAIL

I get ERROR_INVALID_EMAIL when I try to login to firebase but if I replaced _email and _password with the real email and pass from firebase I get Log In FirebaseUser(Instance of 'PlatformUser')
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Login extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return LoginState();
}
}
class LoginState extends State<Login> {
final GlobalKey<FormState> formState = GlobalKey<FormState>();
String _email;
String _password;
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text('Login Page'),
centerTitle: true,
backgroundColor: Colors.deepOrange,
),
body: ListView(
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Form(
key: formState,
child: Container(
child: Column(
children: <Widget>[
TextFormField(
keyboardType: TextInputType.emailAddress,
autofocus: false,
decoration: InputDecoration(
icon: Icon(Icons.email),
hintText: 'Enter Your E-mail',
),
validator: (val) {
if (val.isEmpty) {
return 'Please Enter Your E-mail Address';
}
;
},
onSaved: (val) {
_email = val;
},
),
TextFormField(
autofocus: false,
obscureText: true,
decoration: InputDecoration(
icon: Icon(Icons.vpn_key),
hintText: 'Enter Your Password',
),
validator: (val) {
if (val.isEmpty) {
return 'Enter Your Password';
} else if (val.length < 6) {
return 'Your Password need to be at least 6 characters';
}
;
},
onSaved: (val) {
_password = val;
},
),
RaisedButton(
child: Text('Login'),
onPressed: () async {
final formdata = formState.currentState;
if (formdata.validate()) {
final FirebaseAuth _auth = FirebaseAuth.instance;
formdata.save();
AuthResult result = await _auth.signInWithEmailAndPassword(
email: _email, password: _password)
.catchError((error) => print(error.code));
if (result != null) {
FirebaseUser user = result.user;
if (user != null) {
print('Log In: $user');
}
;
}
;
}
;
},
color: Colors.deepOrange,
textColor: Colors.white,
),
],
),
),
),
],
),
),
],
),
);
}
}
i have updated My question i have provided full code why i'm getting message of invalid email should i remove strings at first or remove _email _password from string

getting data from firebase gives null but after hot reload work fine

after I got my data from firebase the data is null but if I hot reload it works fine. if I comment the lines with the issues the code work fine and submit data correctly to firebase
I tried many methods trying to initState to setState but no use.
I even assumed the build was doen before getting the data from firebase but initState should solve this issue as far as I know. I think i'm missing something here. :(
EDIT:
this is my new attemet useing futureBuilder still the widget loads before the data
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_test/flutter_test.dart';
class UnlockDoor extends StatefulWidget {
UnlockDoorState createState() => new UnlockDoorState();
}
class UnlockDoorState extends State<UnlockDoor> {
final formKey = GlobalKey<FormState>();
String building;
String room;
String name;
String email;
DateTime created;
String comment;
String uid;
#override
void initState() {
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
this.uid = user.uid;
});
Firestore.instance.collection('Users').document(uid).get().then((data) {
this.name = data['Name'];
this.email = data['Email'];
this.building = data['Building'];
this.room = data['Room'];
});
print("uid $uid");
super.initState();
}
void validateAndSubmit() async {
created = DateTime.now();
formKey.currentState.save();
await Firestore.instance
.collection('Requests')
.document('UnlockDoor')
.collection('UnlockDoor')
.document()
.setData({
'Email': email,
'Name': name,
'Building': building,
'Room': room,
'Comment': comment,
'Status': "Pending",
'Created': created,
'Housing_Emp': "",
'UID': uid
});
Navigator.of(context).pop();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Unlock Door Request"),
),
body: new FutureBuilder<DocumentSnapshot>(
future: Firestore.instance.collection('Users').document(uid).get(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.active:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.done:
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
print("why give null $name");
return new Container(
padding: EdgeInsets.only(top: 60.0, left: 20.0, right: 20.0),
child: new Form(
key: formKey,
child: new ListView(
children: <Widget>[
Text(
'Requesting Door Unlock:',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 15.0),
Text(
"building: $building, Room: $room",
style: TextStyle(
fontSize: 15.0,
fontStyle: FontStyle.italic,
),
),
TextFormField(
maxLength: 200,
onSaved: (value) => comment = value,
decoration: InputDecoration(
labelText: 'Comment (optional)',
labelStyle: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
color: Colors.black54),
),
),
Container(
height: 50.0,
width: 130.0,
child: RaisedButton(
child: Text(
'Send Request',
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
splashColor: Colors.lightGreen,
onPressed: () {
_handlePressed(context);
}),
),
],
),
),
);
}
}
},
),
);
}
void _handlePressed(BuildContext context) {
confirmDialog(context).then((bool value) async {
if (value) {
validateAndSubmit();
}
});
}
}
Future<bool> confirmDialog(BuildContext context) {
return showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: new Text("Send Request"),
actions: <Widget>[
new FlatButton(
child: Text("Yes"),
onPressed: () => Navigator.of(context).pop(true),
),
new FlatButton(
child: Text("No"),
onPressed: () => Navigator.of(context).pop(false),
),
],
);
});
}
You are trying to get the document in async task and you are using that value in view(widget). Until the document is fetched from Firebase, the value of document will be null.
Possible solutions:
Use null checks and handle in widget (Not recommend)
Use FutureBuilder which is perfect for your use case. For example, refer
I edited your code. Have a look
class UnlockDoorState extends State<UnlockDoor> {
final formKey = GlobalKey<FormState>();
String building;
String room;
String name;
String email;
DateTime created;
String comment;
String uid;
Future data; //changed
#override
void initState() {
super.initState();
data = getDataFromFb(); //changed
}
Future<void> getDataFromFb() async { //changed
FirebaseUser user = await FirebaseAuth.instance.currentUser();
this.uid = user.uid;
var data = Firestore.instance.collection('Users').document(uid).get();
this.name = data['Name'];
this.email = data['Email'];
this.building = data['Building'];
this.room = data['Room'];
return;
}
void validateAndSubmit() async {
created = DateTime.now();
formKey.currentState.save();
await Firestore.instance
.collection('Requests')
.document('UnlockDoor')
.collection('UnlockDoor')
.document()
.setData({
'Email': email,
'Name': name,
'Building': building,
'Room': room,
'Comment': comment,
'Status': "Pending",
'Created': created,
'Housing_Emp': "",
'UID': uid
});
Navigator.of(context).pop();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Unlock Door Request"),
),
body: new FutureBuilder<DocumentSnapshot>(
future: data, //changed
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.active:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.done:
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
print("why give null $name");
return new Container(
padding: EdgeInsets.only(top: 60.0, left: 20.0, right: 20.0),
child: new Form(
key: formKey,
child: new ListView(
children: <Widget>[
Text(
'Requesting Door Unlock:',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 15.0),
Text(
"building: $building, Room: $room",
style: TextStyle(
fontSize: 15.0,
fontStyle: FontStyle.italic,
),
),
TextFormField(
maxLength: 200,
onSaved: (value) => comment = value,
decoration: InputDecoration(
labelText: 'Comment (optional)',
labelStyle: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
color: Colors.black54),
),
),
Container(
height: 50.0,
width: 130.0,
child: RaisedButton(
child: Text(
'Send Request',
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
splashColor: Colors.lightGreen,
onPressed: () {
_handlePressed(context);
}),
),
],
),
),
);
}
}
},
),
);
}
void _handlePressed(BuildContext context) {
confirmDialog(context).then((bool value) async {
if (value) {
validateAndSubmit();
}
});
}
}

Resources