How to edit firebase existing document with flutter - firebase

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);
});
}

Related

why is my user detail not saving into realtime database?

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.

Problems with using a URL in NetworkImage (flutter)

I am trying to pass a URL that I receive from Firebase to my NetworkImage widget on the AppBar. However, my code keeps passing a null value to my NetworkImage widget. How can I pass the URL properly to the widget.
class DashboardScreen extends StatefulWidget {
#override
_DashboardScreenState createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
Future inputData() async {
final FirebaseAuth auth = FirebaseAuth.instance;
final FirebaseUser user = await auth.currentUser();
final uid = user.uid;
DocumentReference _stock = Firestore.instance.document('users/$uid');
DocumentSnapshot snapshot = await _stock.get();
Map<String, dynamic> data = snapshot.data;
return data['image_url'];
}
String myAvatarUrl;
void converter() {
inputData().then((result) {
myAvatarUrl = result;
print(myAvatarUrl);
});
}
#override
Widget build(BuildContext context) {
converter();
return Scaffold(
appBar: AppBar(
leading: Padding(
padding: EdgeInsets.only(top: 12.0, bottom: 12.0, left: 13.0),
child: CircleAvatar(
backgroundImage: NetworkImage(myAvatarUrl),
child: FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SearchsettingsScreen(),
),
);
},
),
backgroundColor: Colors.white,
),
),
centerTitle: true,
title: Text(
'My Dashboard',
),
backgroundColor: Theme.of(context).primaryColor,
automaticallyImplyLeading: false,
actions: [
DropdownButton(
underline: Container(),
icon: Icon(
Icons.more_vert,
color: Theme.of(context).primaryIconTheme.color,
),
items: [
DropdownMenuItem(
child: Container(
child: Row(
children: <Widget>[
Icon(
Icons.exit_to_app,
),
SizedBox(
width: 8.0,
),
Text('Logout'),
],
),
),
value: 'logout',
),
],
onChanged: (itemIdentifier) {
if (itemIdentifier == 'logout') {
FirebaseAuth.instance.signOut();
}
},
),
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ReusableDashboardSettingCard(),
ReusableDashboardContactsCard(),
],
),
);
}
}
This is the error I get on my console:
The following assertion was thrown building DashboardScreen(dirty, state: _DashboardScreenState#e1615):
'package:flutter/src/painting/_network_image_io.dart': Failed assertion: line 26 pos 14: 'url != null': is not true.
Your main errors are:
you are not managing that there is the possibility that myAvatarUrl can be null
you are not telling to Flutter to rebuild your widget when data will arrive using setState((){})
I suggest you take a look at Codelabs and Fetch data from the internet.
I've not tested it but it should work
import 'package:flutter/material.dart';
class DashboardScreen extends StatefulWidget {
#override
_DashboardScreenState createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
String myAvatarUrl;
Future inputData() async {
final FirebaseAuth auth = FirebaseAuth.instance;
final FirebaseUser user = await auth.currentUser();
final uid = user.uid;
DocumentReference _stock = Firestore.instance.document('users/$uid');
DocumentSnapshot snapshot = await _stock.get();
Map<String, dynamic> data = snapshot.data;
return data['image_url'];
}
#override
void initState() {
super.initState();
// When data will arrive
inputData().then((value) {
setState(() => myAvatarUrl = value);
print(myAvatarUrl);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: myAvatarUrl == null
? const SizedBox()
: Padding(
padding: EdgeInsets.only(top: 12.0, bottom: 12.0, left: 13.0),
child: CircleAvatar(
backgroundImage: NetworkImage(myAvatarUrl),
child: FlatButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SearchsettingsScreen(),
),
);
},
),
backgroundColor: Colors.white,
),
),
centerTitle: true,
title: Text(
'My Dashboard',
),
backgroundColor: Theme.of(context).primaryColor,
automaticallyImplyLeading: false,
actions: [
DropdownButton(
underline: Container(),
icon: Icon(
Icons.more_vert,
color: Theme.of(context).primaryIconTheme.color,
),
items: [
DropdownMenuItem(
child: Container(
child: Row(
children: <Widget>[
Icon(
Icons.exit_to_app,
),
SizedBox(
width: 8.0,
),
Text('Logout'),
],
),
),
value: 'logout',
),
],
onChanged: (itemIdentifier) {
if (itemIdentifier == 'logout') {
FirebaseAuth.instance.signOut();
}
},
),
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ReusableDashboardSettingCard(),
ReusableDashboardContactsCard(),
],
),
);
}
}

A non-null String must be provided to a Text widget flutter

I have this problem with this code. I tried to solve the problem, but I did not succeed. Please Help
Please see the screenshots to understand the problem well
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
Pictures description error
null in firebase
The users email address.Will be null if signing in anonymously.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flash_chat/constants.dart';
class ChatScreen extends StatefulWidget {
static const Id = 'chat_screen';
#override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
// ignore: deprecated_member_use
final _firestore = Firestore.instance;
final _auth = FirebaseAuth.instance;
// ignore: deprecated_member_use
FirebaseUser loggedInUser;
String messageText;
#override
void initState() {
super.initState();
getCurrentUser();
}
void getCurrentUser() async {
try {
// ignore: await_only_futures
final user = await _auth.currentUser;
if (user != null) {
loggedInUser = user;
print(loggedInUser.email);
}
} catch (e) {
print(e);
}
}
// void getMessages() async {
// // ignore: deprecated_member_use
// final messages = await _firestore.collection('Messages').getDocuments();
// // ignore: deprecated_member_use
// for (var message in messages.docs) {
// print(message.data());
// }
// }
void messagesStream() async {
await for (var snapshot in _firestore.collection('Messages').snapshots()) {
for (var message in snapshot.docs) {
print(message.data());
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
messagesStream();
//_auth.signOut();
//Navigator.pop(context);
}),
],
title: Text('⚡️Chat'),
backgroundColor: Colors.lightBlueAccent,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('Messages').snapshots(),
// ignore: missing_return
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.lightBlueAccent,
));
}
// ignore: deprecated_member_use
final messages = snapshot.data.documents;
List<Messagebubble> messagebubbles = [];
for (var message in messages) {
final messageText = message.data()['text'];
final messagesendar = message.data()['Sender'];
final messagebubble = Messagebubble(
sendar: messagesendar,
text: messageText,
);
messagebubbles.add(messagebubble);
}
return Expanded(
child: ListView(
padding: EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 20.0,
),
children: messagebubbles,
),
);
},
),
Container(
decoration: kMessageContainerDecoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
onChanged: (value) {
messageText = value;
},
decoration: kMessageTextFieldDecoration,
),
),
FlatButton(
onPressed: () {
_firestore.collection('Messages').add({
'text': messageText,
'Sender': loggedInUser,
});
},
child: Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}
class Messagebubble extends StatelessWidget {
Messagebubble({
Key key,
this.sendar,
this.text,
}) : super(key: key);
final String sendar;
final String text;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(10.0),
child: Column(
children: [
Text(
sendar,
style: TextStyle(
fontSize: 12.0,
color: Colors.black54,
),
),
Material(
borderRadius: BorderRadius.circular(30.0),
elevation: 5.0,
color: Colors.lightBlueAccent,
child: Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 20.0,
),
child: Text(
text,
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
),
),
),
),
],
),
);
}
}
You just need to check whether the text that you are passing is null or not. If it is null, you can show that the user is Anonymous.
final messageText = message.data()['text'];
final messagesendar = message.data()['Sender'] ?? 'Anonymous'; // If null then use 'Anonymous'
final messagebubble = Messagebubble(
sendar: messagesendar,
text: messageText,
);
Flutter doesn't allow you to pass null to Text widgets.

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

Resources