below is my code, i have a chat made in flutter and it should be sorted by timestamp however it is still seemingly random, on firebase it is recording the correct time stamp in json and i thought i had it coded correctly with the firestore.collection order by call. image attached shows the messages they should be ordered 1-6
import 'package:flutter/material.dart';
import 'package:bardsf/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
late String messageText;
class BodyBuildingChat extends StatefulWidget {
static const String id = 'body_building_chat';
#override
_BodyBuildingChatState createState() => _BodyBuildingChatState();
}
class _BodyBuildingChatState extends State<BodyBuildingChat> {
final messageTextController = TextEditingController();
final _firestore = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance;
late User loggedInUser;
#override
void initState() {
super.initState();
getCurrentUser();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
loggedInUser = user;
print(loggedInUser.email);
}
} catch (e) {
print (e);
}
}
// void getMessages() async{
// final messages = await _firestore.collection('messages').get();
// for (var message in messages.docs) {
// print(message.data().cast());
// }
// }
void messagesStream() async {
await for( var snapshot in _firestore.collection('bodybuilding').orderBy('timestamp').snapshots()) {
for (var message in snapshot.docs) {
print(message.data().cast());
}
}
}
#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('🏔Body Building'),
backgroundColor: Colors.lightBlueAccent,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('bodybuilding').snapshots(),
builder: (context, snapshot){
List<MessageBubble> messageBubbles = [];
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.lightBlueAccent,
),
);
}
final messages = snapshot.data!.docs.reversed;
for (var message in messages) {
final messageText = message['text'];
final messageSender = message['sender'];
final currentUser = loggedInUser.email;
final messageBubble = MessageBubble(
sender: messageSender,
text: messageText,
isMe: currentUser == messageSender,
);
messageBubbles.add(messageBubble);
}
return Expanded(
child: ListView(
reverse: true,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
children: messageBubbles,
),
);
},
),
Container(
decoration: kMessageContainerDecoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
controller: messageTextController,
onChanged: (value) {
messageText = value;
},
decoration: kMessageTextFieldDecoration,
),
),
TextButton(
onPressed: () {
messageTextController.clear();
_firestore.collection('bodybuilding').add({
'text': messageText,
'sender': loggedInUser.email,
'timestamp': FieldValue.serverTimestamp(),
});
},
child: Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}
class MessageBubble extends StatelessWidget {
MessageBubble({required this.sender,required this.text,required this.isMe});
final String sender;
final String text;
final bool isMe;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: <Widget>[
Text(sender,
style: TextStyle(
fontSize: 12.0,
),
),
Material(
borderRadius: isMe ? BorderRadius.only(topLeft: Radius.circular(30.0),
bottomLeft: Radius.circular(30.0),
bottomRight: Radius.circular(30.0),
) : BorderRadius.only(topRight: Radius.circular(30.0),
bottomLeft: Radius.circular(30.0),
bottomRight: Radius.circular(30.0),
),
elevation: 5.0,
color: isMe ? Colors.lightBlueAccent : Colors.white,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 8.0),
child: Text('$text',
style: TextStyle( fontSize: 15.0,
color: isMe ? Colors.white : Colors.black,),
),
),
),
],
),
);
}
}
You did not use the appropriate stream.
Change this line
stream: _firestore.collection('bodybuilding').snapshots(),
into this line
stream: _firestore.collection('bodybuilding').orderBy('timestamp').snapshots(),
You will notice that you used the correct stream in the messagesStream but not in the StremBuilder.
Let me know if this does not help.
i went through google code lab of flutter firebase using provider package every thing working fine as mentioned in codelab i like the way they design Authentication widget passing functions from it, in below code i want to add CircularProgressIndicator on waiting state, i don't understand where do i add condition of isLoading is equals to true then wait otherwise dosomething with functions passed by Authentication widget.
main.dart
import 'package:firebase_core/firebase_core.dart'; // new
import 'package:firebase_auth/firebase_auth.dart'; // new
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart'; // new
import 'src/authentication.dart'; // new
import 'src/widgets.dart';
void main() {
// Modify from here
runApp(
ChangeNotifierProvider(
create: (context) => ApplicationState(),
builder: (context, _) => App(),
),
);
// to here.
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Meetup',
theme: ThemeData(
buttonTheme: Theme.of(context).buttonTheme.copyWith(
highlightColor: Colors.deepPurple,
),
primarySwatch: Colors.deepPurple,
textTheme: GoogleFonts.robotoTextTheme(
Theme.of(context).textTheme,
),
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Firebase Meetup'),
),
body: ListView(
children: <Widget>[
Image.asset('assets/codelab.png'),
SizedBox(height: 8),
IconAndDetail(Icons.calendar_today, 'October 30'),
IconAndDetail(Icons.location_city, 'San Francisco'),
// Add from here
Consumer<ApplicationState>(
builder: (context, appState, _) => Authentication(
email: appState.email,
loginState: appState.loginState,
startLoginFlow: appState.startLoginFlow,
verifyEmail: appState.verifyEmail,
signInWithEmailAndPassword: appState.signInWithEmailAndPassword,
cancelRegistration: appState.cancelRegistration,
registerAccount: appState.registerAccount,
signOut: appState.signOut,
),
),
// to here
Divider(
height: 8,
thickness: 1,
indent: 8,
endIndent: 8,
color: Colors.grey,
),
Header("What we'll be doing"),
Paragraph(
'Join us for a day full of Firebase Workshops and Pizza!',
),
],
),
);
}
}
class ApplicationState extends ChangeNotifier {
ApplicationState() {
init();
}
Future<void> init() async {
await Firebase.initializeApp();
FirebaseAuth.instance.userChanges().listen((user) {
if (user != null) {
_loginState = ApplicationLoginState.loggedIn;
} else {
_loginState = ApplicationLoginState.loggedOut;
}
notifyListeners();
});
}
ApplicationLoginState _loginState = ApplicationLoginState.loggedOut;
ApplicationLoginState get loginState => _loginState;
String? _email;
String? get email => _email;
void startLoginFlow() {
_loginState = ApplicationLoginState.emailAddress;
notifyListeners();
}
void verifyEmail(
String email,
void Function(FirebaseAuthException e) errorCallback,
) async {
try {
var methods = await FirebaseAuth.instance.fetchSignInMethodsForEmail(email);
if (methods.contains('password')) {
_loginState = ApplicationLoginState.password;
} else {
_loginState = ApplicationLoginState.register;
}
_email = email;
notifyListeners();
} on FirebaseAuthException catch (e) {
errorCallback(e);
}
}
void signInWithEmailAndPassword(
String email,
String password,
void Function(FirebaseAuthException e) errorCallback,
) async {
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
} on FirebaseAuthException catch (e) {
errorCallback(e);
}
}
void cancelRegistration() {
_loginState = ApplicationLoginState.emailAddress;
notifyListeners();
}
void registerAccount(String email, String displayName, String password,
void Function(FirebaseAuthException e) errorCallback) async {
try {
var credential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
await credential.user!.updateProfile(displayName: displayName);
} on FirebaseAuthException catch (e) {
errorCallback(e);
}
}
void signOut() {
FirebaseAuth.instance.signOut();
/// here is not notifylistener();
}
}
authentication.dart
import 'package:flutter/material.dart';
import 'widgets.dart';
enum ApplicationLoginState {
loggedOut,
emailAddress,
register,
password,
loggedIn,
}
class Authentication extends StatelessWidget {
const Authentication({
required this.loginState,
required this.email,
required this.startLoginFlow,
required this.verifyEmail,
required this.signInWithEmailAndPassword,
required this.cancelRegistration,
required this.registerAccount,
required this.signOut,
});
final ApplicationLoginState loginState;
final String? email;
final void Function() startLoginFlow;
final void Function(
String email,
void Function(Exception e) error,
) verifyEmail;
final void Function(
String email,
String password,
void Function(Exception e) error,
) signInWithEmailAndPassword;
final void Function() cancelRegistration;
final void Function(
String email,
String displayName,
String password,
void Function(Exception e) error,
) registerAccount;
final void Function() signOut;
#override
Widget build(BuildContext context) {
switch (loginState) {
case ApplicationLoginState.loggedOut:
return Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 24, bottom: 8),
child: StyledButton(
onPressed: () {
startLoginFlow();
},
child: const Text('RSVP'),
),
),
],
);
case ApplicationLoginState.emailAddress:
return EmailForm(
callback: (email) =>
verifyEmail(email, (e) => _showErrorDialog(context, 'Invalid email', e)));
case ApplicationLoginState.password:
return PasswordForm(
email: email!,
login: (email, password) {
print("CONTEXT $context");
signInWithEmailAndPassword(
email, password, (e) => _showErrorDialog(context, 'Failed to sign in', e));
},
);
case ApplicationLoginState.register:
return RegisterForm(
email: email!,
cancel: () {
cancelRegistration();
},
registerAccount: (
email,
displayName,
password,
) {
registerAccount(email, displayName, password,
(e) => _showErrorDialog(context, 'Failed to create account', e));
},
);
case ApplicationLoginState.loggedIn:
return Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 24, bottom: 8),
child: StyledButton(
onPressed: () {
signOut();
},
child: const Text('LOGOUT'),
),
),
],
);
default:
return Row(
children: const [
Text("Internal error, this shouldn't happen..."),
],
);
}
}
void _showErrorDialog(BuildContext context, String title, Exception e) {
print("CONTEXT $context");
showDialog<void>(
context: context,
builder: (context) {
return AlertDialog(
title: Text(
title,
style: const TextStyle(fontSize: 24),
),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text(
'${(e as dynamic).message}',
style: const TextStyle(fontSize: 18),
),
],
),
),
actions: <Widget>[
StyledButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'OK',
style: TextStyle(color: Colors.deepPurple),
),
),
],
);
},
);
}
}
class EmailForm extends StatefulWidget {
const EmailForm({required this.callback});
final void Function(String email) callback;
#override
_EmailFormState createState() => _EmailFormState();
}
class _EmailFormState extends State<EmailForm> {
final _formKey = GlobalKey<FormState>(debugLabel: '_EmailFormState');
final _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return Column(
children: [
const Header('Sign in with email'),
Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your email address to continue';
}
return null;
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 30),
child: StyledButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
widget.callback(_controller.text);
}
},
child: const Text('NEXT'),
),
),
],
),
],
),
),
),
],
);
}
}
class RegisterForm extends StatefulWidget {
const RegisterForm({
required this.registerAccount,
required this.cancel,
required this.email,
});
final String email;
final void Function(String email, String displayName, String password) registerAccount;
final void Function() cancel;
#override
_RegisterFormState createState() => _RegisterFormState();
}
class _RegisterFormState extends State<RegisterForm> {
final _formKey = GlobalKey<FormState>(debugLabel: '_RegisterFormState');
final _emailController = TextEditingController();
final _displayNameController = TextEditingController();
final _passwordController = TextEditingController();
#override
void initState() {
super.initState();
_emailController.text = widget.email;
}
#override
Widget build(BuildContext context) {
return Column(
children: [
const Header('Create account'),
Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _emailController,
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your email address to continue';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _displayNameController,
decoration: const InputDecoration(
hintText: 'First & last name',
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your account name';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
hintText: 'Password',
),
obscureText: true,
validator: (value) {
if (value!.isEmpty) {
return 'Enter your password';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: widget.cancel,
child: const Text('CANCEL'),
),
const SizedBox(width: 16),
StyledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
widget.registerAccount(
_emailController.text,
_displayNameController.text,
_passwordController.text,
);
}
},
child: const Text('SAVE'),
),
const SizedBox(width: 30),
],
),
),
],
),
),
),
],
);
}
}
class PasswordForm extends StatefulWidget {
const PasswordForm({
required this.login,
required this.email,
});
final String email;
final void Function(String email, String password) login;
#override
_PasswordFormState createState() => _PasswordFormState();
}
class _PasswordFormState extends State<PasswordForm> {
final _formKey = GlobalKey<FormState>(debugLabel: '_PasswordFormState');
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
#override
void initState() {
super.initState();
_emailController.text = widget.email;
}
#override
Widget build(BuildContext context) {
return Column(
children: [
const Header('Sign in'),
Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _emailController,
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your email address to continue';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
hintText: 'Password',
),
obscureText: true,
validator: (value) {
if (value!.isEmpty) {
return 'Enter your password';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const SizedBox(width: 16),
StyledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
widget.login(
_emailController.text,
_passwordController.text,
);
}
},
child: const Text('SIGN IN'),
),
const SizedBox(width: 30),
],
),
),
],
),
),
),
],
);
}
}
widgets.dart
import 'package:flutter/material.dart';
class Header extends StatelessWidget {
const Header(this.heading);
final String heading;
#override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
heading,
style: const TextStyle(fontSize: 24),
),
);
}
class Paragraph extends StatelessWidget {
const Paragraph(this.content);
final String content;
#override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Text(
content,
style: const TextStyle(fontSize: 18),
),
);
}
class IconAndDetail extends StatelessWidget {
const IconAndDetail(this.icon, this.detail);
final IconData icon;
final String detail;
#override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Icon(icon),
const SizedBox(width: 8),
Text(
detail,
style: const TextStyle(fontSize: 18),
)
],
),
);
}
class StyledButton extends StatelessWidget {
const StyledButton({required this.child, required this.onPressed});
final Widget child;
final void Function() onPressed;
#override
Widget build(BuildContext context) => OutlinedButton(
style: OutlinedButton.styleFrom(
side: const BorderSide(color: Colors.deepPurple)),
onPressed: onPressed,
child: child,
);
}
pubspec.yaml (version numbers at time of posting)
cloud_firestore: ^1.0.0 # new
firebase_auth: ^1.0.0 # new
google_fonts: ^2.0.0
provider: ^5.0.0
I answer my question, you could do this by adding bool isLoading variable in ApplicationState class and set its value on conditioned base from any method(signInWithEmailAndPassword) present in ApplicationState and pass isLoading to Authentication widget and check condition in build method e.g if isLoading true then show CircularProgressIndicator check below code for more details:
main.dart
import 'package:firebase_core/firebase_core.dart'; // new
import 'package:firebase_auth/firebase_auth.dart'; // new
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart'; // new
import 'src/authentication.dart'; // new
import 'src/widgets.dart';
void main() {
// Modify from here
runApp(
ChangeNotifierProvider(
create: (context) => ApplicationState(),
builder: (context, _) => App(),
),
);
// to here.
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Meetup',
theme: ThemeData(
buttonTheme: Theme.of(context).buttonTheme.copyWith(
highlightColor: Colors.deepPurple,
),
primarySwatch: Colors.deepPurple,
textTheme: GoogleFonts.robotoTextTheme(
Theme.of(context).textTheme,
),
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Firebase Meetup'),
),
body: ListView(
children: <Widget>[
Image.asset('assets/codelab.png'),
SizedBox(height: 8),
IconAndDetail(Icons.calendar_today, 'October 30'),
IconAndDetail(Icons.location_city, 'San Francisco'),
// Add from here
Consumer<ApplicationState>(
builder: (context, appState, _) => Authentication(
isLoading: appState.isLoading,
email: appState.email,
loginState: appState.loginState,
startLoginFlow: appState.startLoginFlow,
verifyEmail: appState.verifyEmail,
signInWithEmailAndPassword: appState.signInWithEmailAndPassword,
cancelRegistration: appState.cancelRegistration,
registerAccount: appState.registerAccount,
signOut: appState.signOut,
),
),
// to here
Divider(
height: 8,
thickness: 1,
indent: 8,
endIndent: 8,
color: Colors.grey,
),
Header("What we'll be doing"),
Paragraph(
'Join us for a day full of Firebase Workshops and Pizza!',
),
],
),
);
}
}
class ApplicationState extends ChangeNotifier {
ApplicationState() {
init();
}
Future<void> init() async {
await Firebase.initializeApp();
FirebaseAuth.instance.userChanges().listen((user) {
if (user != null) {
_loginState = ApplicationLoginState.loggedIn;
} else {
_loginState = ApplicationLoginState.loggedOut;
}
notifyListeners();
});
}
ApplicationLoginState _loginState = ApplicationLoginState.loggedOut;
ApplicationLoginState get loginState => _loginState;
bool get isLoading => _isLoading;
String? _email;
String? get email => _email;
bool _isLoading = false;
void startLoginFlow() {
_loginState = ApplicationLoginState.emailAddress;
notifyListeners();
}
void verifyEmail(
String email,
void Function(FirebaseAuthException e) errorCallback,
) async {
try {
var methods = await FirebaseAuth.instance.fetchSignInMethodsForEmail(email);
if (methods.contains('password')) {
_loginState = ApplicationLoginState.password;
} else {
_loginState = ApplicationLoginState.register;
}
_email = email;
notifyListeners();
} on FirebaseAuthException catch (e) {
errorCallback(e);
}
}
void signInWithEmailAndPassword(
String email,
String password,
void Function(FirebaseAuthException e) errorCallback,
) async {
try {
if (!this.isLoading) {
this._isLoading = true;
notifyListeners();
}
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
} on FirebaseAuthException catch (e) {
errorCallback(e);
this._isLoading = false;
notifyListeners();
}
}
void cancelRegistration() {
_loginState = ApplicationLoginState.emailAddress;
notifyListeners();
}
void registerAccount(String email, String displayName, String password,
void Function(FirebaseAuthException e) errorCallback) async {
try {
var credential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
await credential.user!.updateProfile(displayName: displayName);
} on FirebaseAuthException catch (e) {
errorCallback(e);
}
}
void signOut() {
FirebaseAuth.instance.signOut();
/// here is not notifylistener();
}
}
authentication.dart
import 'package:flutter/material.dart';
import 'widgets.dart';
enum ApplicationLoginState {
loggedOut,
emailAddress,
register,
password,
loggedIn,
}
class Authentication extends StatelessWidget {
const Authentication({
required this.isLoading,
required this.loginState,
required this.email,
required this.startLoginFlow,
required this.verifyEmail,
required this.signInWithEmailAndPassword,
required this.cancelRegistration,
required this.registerAccount,
required this.signOut,
});
final bool isLoading;
final ApplicationLoginState loginState;
final String? email;
final void Function() startLoginFlow;
final void Function(
String email,
void Function(Exception e) error,
) verifyEmail;
final void Function(
String email,
String password,
void Function(Exception e) error,
) signInWithEmailAndPassword;
final void Function() cancelRegistration;
final void Function(
String email,
String displayName,
String password,
void Function(Exception e) error,
) registerAccount;
final void Function() signOut;
#override
Widget build(BuildContext context) {
if (this.isLoading) {
return Stack(
children: [Center(child: CircularProgressIndicator(value: null))],
);
}
switch (loginState) {
case ApplicationLoginState.loggedOut:
return Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 24, bottom: 8),
child: StyledButton(
onPressed: () {
startLoginFlow();
},
child: const Text('RSVP'),
),
),
],
);
case ApplicationLoginState.emailAddress:
return EmailForm(
callback: (email) =>
verifyEmail(email, (e) => _showErrorDialog(context, 'Invalid email', e)));
case ApplicationLoginState.password:
return PasswordForm(
email: email!,
login: (email, password) {
print("CONTEXT $context");
signInWithEmailAndPassword(
email, password, (e) => _showErrorDialog(context, 'Failed to sign in', e));
},
);
case ApplicationLoginState.register:
return RegisterForm(
email: email!,
cancel: () {
cancelRegistration();
},
registerAccount: (
email,
displayName,
password,
) {
registerAccount(email, displayName, password,
(e) => _showErrorDialog(context, 'Failed to create account', e));
},
);
case ApplicationLoginState.loggedIn:
return Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 24, bottom: 8),
child: StyledButton(
onPressed: () {
signOut();
},
child: const Text('LOGOUT'),
),
),
],
);
default:
return Row(
children: const [
Text("Internal error, this shouldn't happen..."),
],
);
}
}
void _showErrorDialog(BuildContext context, String title, Exception e) {
print("CONTEXT $context");
showDialog<void>(
context: context,
builder: (context) {
return AlertDialog(
title: Text(
title,
style: const TextStyle(fontSize: 24),
),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text(
'${(e as dynamic).message}',
style: const TextStyle(fontSize: 18),
),
],
),
),
actions: <Widget>[
StyledButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'OK',
style: TextStyle(color: Colors.deepPurple),
),
),
],
);
},
);
}
}
class EmailForm extends StatefulWidget {
const EmailForm({required this.callback});
final void Function(String email) callback;
#override
_EmailFormState createState() => _EmailFormState();
}
class _EmailFormState extends State<EmailForm> {
final _formKey = GlobalKey<FormState>(debugLabel: '_EmailFormState');
final _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return Column(
children: [
const Header('Sign in with email'),
Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your email address to continue';
}
return null;
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 30),
child: StyledButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
widget.callback(_controller.text);
}
},
child: const Text('NEXT'),
),
),
],
),
],
),
),
),
],
);
}
}
class RegisterForm extends StatefulWidget {
const RegisterForm({
required this.registerAccount,
required this.cancel,
required this.email,
});
final String email;
final void Function(String email, String displayName, String password) registerAccount;
final void Function() cancel;
#override
_RegisterFormState createState() => _RegisterFormState();
}
class _RegisterFormState extends State<RegisterForm> {
final _formKey = GlobalKey<FormState>(debugLabel: '_RegisterFormState');
final _emailController = TextEditingController();
final _displayNameController = TextEditingController();
final _passwordController = TextEditingController();
#override
void initState() {
super.initState();
_emailController.text = widget.email;
}
#override
Widget build(BuildContext context) {
return Column(
children: [
const Header('Create account'),
Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _emailController,
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your email address to continue';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _displayNameController,
decoration: const InputDecoration(
hintText: 'First & last name',
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your account name';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
hintText: 'Password',
),
obscureText: true,
validator: (value) {
if (value!.isEmpty) {
return 'Enter your password';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: widget.cancel,
child: const Text('CANCEL'),
),
const SizedBox(width: 16),
StyledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
widget.registerAccount(
_emailController.text,
_displayNameController.text,
_passwordController.text,
);
}
},
child: const Text('SAVE'),
),
const SizedBox(width: 30),
],
),
),
],
),
),
),
],
);
}
}
class PasswordForm extends StatefulWidget {
const PasswordForm({
required this.login,
required this.email,
});
final String email;
final void Function(String email, String password) login;
#override
_PasswordFormState createState() => _PasswordFormState();
}
class _PasswordFormState extends State<PasswordForm> {
final _formKey = GlobalKey<FormState>(debugLabel: '_PasswordFormState');
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
#override
void initState() {
super.initState();
_emailController.text = widget.email;
}
#override
Widget build(BuildContext context) {
return Column(
children: [
const Header('Sign in'),
Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _emailController,
decoration: const InputDecoration(
hintText: 'Enter your email',
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter your email address to continue';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
hintText: 'Password',
),
obscureText: true,
validator: (value) {
if (value!.isEmpty) {
return 'Enter your password';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const SizedBox(width: 16),
StyledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
widget.login(
_emailController.text,
_passwordController.text,
);
}
},
child: const Text('SIGN IN'),
),
const SizedBox(width: 30),
],
),
),
],
),
),
),
],
);
}
}
Tried signing up user with Firebase but got the above error instead, and the code is formatted in such a way that it should redirect the user to homepage after a successful signup.
My main.dart
import 'package:bedc_app/home_page.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:bedc_app/auth/login_page.dart';
void main() async{
//solution study
WidgetsFlutterBinding.ensureInitialized();
FirebaseAuth.instance.currentUser()
.then((FirebaseUser user) {
if(user != null){
Firestore.instance.collection('users').document(user.uid).get().then((DocumentSnapshot doc){
runApp(MyApp(true, doc));
});
return;
}
runApp(MyApp(false, null));
});
}
// void main() =>runApp(MyApp());
class MyApp extends StatelessWidget {
bool isLoggedIn;
DocumentSnapshot doc;
MyApp(this.isLoggedIn, this.doc);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Multifunctional bedc project App',
debugShowCheckedModeBanner: false,
home: isLoggedIn ? HomePage(userDoc: doc) : loginPage(),
);
}
}
My Signup_page.dart
import 'package:bedc_app/auth/login_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:bedc_app/utils/constants.dart';
import '../home_page.dart';
class SignUpPage extends StatefulWidget {
#override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
String email, password;
bool isLoggedIn = false;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: ListView(
children: [
SizedBox(
height: 50,
),
Align(
alignment: Alignment.topCenter,
child: (
Image.asset(
'assets/bedclogo.jpg'
)),
),
SizedBox(
height: 100,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 26.0),
child: TextField(
decoration: InputDecoration(
hintText: 'email',
border: OutlineInputBorder(),
labelText: 'Email',
suffixIcon: Icon(Icons.email, color: Colors.green)
),
keyboardType: TextInputType.emailAddress,
onChanged: (String val){
email = val;
},
),
),
SizedBox(
height: 10,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 26.0),
child: TextField(
decoration: InputDecoration(
hintText: 'Password',
border: OutlineInputBorder(),
labelText: 'Password',
suffixIcon: Icon(Icons.lock, color: Colors.green)
),
obscureText: true,
obscuringCharacter: '!',
keyboardType: TextInputType.emailAddress,
onChanged: (String val){
password = val;
},
),),
SizedBox(
height: 5,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 26),
child: MaterialButton(
color: Color(0xFF88C540),
child: isLoading ? Container(
height: 24,
width: 24,
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
strokeWidth: 2,
)
):Text(
'SignUp'.toUpperCase(),
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: (){
checkUserInput();
},
),
),
SizedBox(
height: 10,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: RichText(
text: TextSpan(
text: 'Already have an Account ?',
style: TextStyle(color: Colors.black),
children: [
TextSpan(
text: 'Login here',
style: TextStyle(color: Colors.blue),
recognizer: TapGestureRecognizer()..onTap = (){
Navigator.of(context).pushReplacement(CupertinoPageRoute(builder: (_) => loginPage()));
},
)
]
)),
)
],
));
}
//SIGNUP FUNCTION USING FIREBASE
bool isLoading = false;
signUpUserWithFirebase(){
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password
).then((AuthResult result){
//Authresult cant be stored to string.....
storeUserDataToFirestore(result.user.uid);
if(result.user.uid != null){
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomePage()));
}
}).catchError((e){
print(e);
isLoading = false;
setState(() { });
});
}
//storeUserDataToFirestore
storeUserDataToFirestore(String userId){
Map<String, dynamic> userData = Map<String, dynamic>();
userData = {
Constants.USERNAME: '#username',
Constants.USER_ID: userId,
Constants.EMAIL : email,
Constants.ACCOUNT_NUM : '00000000',
Constants.IS_ADMIN: false,
Constants.PROFILE_IMAGE: '',
Constants.PROFILE_IMAGE_THUMB: '',
};
CollectionReference usersRef = Firestore.instance.collection(Constants.USERS_COLLECTION);
usersRef.document(userId).setData(userData).then((_){
isLoading = false;
setState(() { });
}).catchError((e){
print(e);
});
}
//FUNCTION TO CHECK USER ENTRY
checkUserInput(){
isLoading = true;
setState(() { });
if(email == null || email.isEmpty){
print('Enter email');
isLoading = false;
setState(() { });
return;
}
if(password == null || email.isEmpty){
print('Enter password');
isLoading = false;
setState(() { });
}
//SIGNUP THE USER
signUpUserWithFirebase();
}
getUserData(String UserId){
Firestore.instance.collection(Constants.USERS_COLLECTION)
.document(UserId)
.get().then((DocumentSnapshot userDoc){
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(CupertinoPageRoute(builder: (_) => HomePage(userDoc: userDoc)));
}).catchError((e){
print(e);
});
}
}
My Home_page.dart
import 'dart:ui';
import 'package:bedc_app/auth/login_page.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:bedc_app/auth/signup_page.dart';
import 'model/user.dart';
User currentUser;
class HomePage extends StatefulWidget {
DocumentSnapshot userDoc;
HomePage({this.userDoc,});
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//user cant access this page unless logged in
bool userIsLoggedIn = true;
#override
void initState() {
// TODO: implement initState
super.initState();
currentUser = User.fromSnapshot(widget.userDoc);
}
//HERE IS BUILDING PROFILE IMAGE
Widget buildProfileImage(){
if(currentUser.profileImage == ''){
return CircleAvatar(
backgroundColor: Colors.white70,
radius: 20,
child: Icon(Icons.person, size: 30),
);
}else{
return CircleAvatar(
backgroundImage: NetworkImage(currentUser.profileImage),
);
}
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.brown,
title: Text('Homepage'),
),
body: ListView(
children: [
SizedBox(height: 20),
Align(
alignment: Alignment.topRight,
child: (
Image.asset(
'assets/bedclogo.jpg',
scale: 2,
)),
),
ListTile(
title: Text(currentUser.username, style: TextStyle(color: Colors.brown, fontWeight: FontWeight.bold),),
leading: buildProfileImage(),
),
SizedBox(height: 30),
//CAPTURE METER READING UI
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: GestureDetector(
onTap: (){
//print(currentUser.isAdmin);
},
child: Row(
children: [
//CAPTURE METR READING
Container(
width: 100,
height: 100,
color: Colors.green,
child: Align(
alignment: Alignment.center,
child: (
Image.asset(
'assets/meterIcon.png',
scale: 3,
)),
),
),
Container(
width: 100,
height: 100,
child: Align(
alignment: Alignment.center,
child: Text('Capture Meter Reading'.toUpperCase()),
),
),
],
),
),
),
SizedBox(height: 30),
//UPDATE PROFILE UI DESIGN
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: GestureDetector(
onTap:(){
//print(currentUser.isAdmin);
},
child: Row(
children: [
Container(
width: 100,
height: 100,
color: Colors.green,
child: Align(
alignment: Alignment.center,
child: (
Image.asset(
'assets/profileAvatar.png',
scale: 3,
)),
),
),
Container(
width: 100,
height: 100,
child: Align(
alignment: Alignment.center,
child: Text('Update Profile'.toUpperCase()),
),
),
],
),
),
),
// TextButton (
// onPressed: (){
// //just logout, implement pop dialog later
// // FirebaseAuth.instance.signOut();
// // Navigator.of(context).pushReplacement(CupertinoPageRoute(builder: (_)=> loginPage()));
// // currentUser = null;
// // setState(() {
// // });
// // still showing error... try to fix asap
// FirebaseAuth.instance.signOut().then((_){
// userIsLoggedIn = false;
// Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_)=> loginPage()));
// //currentUser = null;
// setState(() {
//
// });
// });
// },
// child: Text('SignOut'))
],
)
);
}
}
User.dart for user Model
import 'package:bedc_app/utils/constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class User{
String username;
String email;
String userId;
String accountNum;
bool isAdmin;
String profileImage;
String profileImageThumb;
User({
this.username,
this.email,
this.userId,
this.accountNum,
this.isAdmin,
this.profileImage,
this.profileImageThumb
});
factory User.fromSnapshot(DocumentSnapshot doc){
return User(
username: doc.data[Constants.USERNAME],
email: doc.data[Constants.EMAIL],
userId: doc.data[Constants.USER_ID],
accountNum: doc.data[Constants.ACCOUNT_NUM],
isAdmin: doc.data[Constants.IS_ADMIN],
profileImage: doc.data[Constants.PROFILE_IMAGE],
profileImageThumb: doc.data[Constants.PROFILE_IMAGE_THUMB]
);
}
}
Having signed the user up, im getting error The getter 'data' was called on null. Receiver: null Tried calling: data.
i dont know which part of the code is causing this exception
This error generally show when you try to get some attribute on null object.
In your case, call one of doc.data[..] in file User.dart generate the error that means doc == null is true.
Verify that widget.userDoc is not null at this line currentUser = User.fromSnapshot(widget.userDoc); on initState method of Home_page.dart file
So error provide in one of HomePage call who require a non null userDoc (todo: make sure your data is not null using assert and add #required before required variable on your class exp: HomePage({#required this.userDoc,}): assert(userDoc != null, "BOooh my userDoc may be not null"); that help very much when you debug your app)
finaly your problem provide in signUpUserWithFirebase() method of your Signup_page.dart file... here Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomePage()));
Try to replace by this getUserData(result.user.uid) so your methode should become
signUpUserWithFirebase(){
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password
).then((AuthResult result){
//Authresult cant be stored to string.....
storeUserDataToFirestore(result.user.uid);
if(result.user.uid != null){
getUserData(result.user.uid); // replaced line
}
}).catchError((e){
print(e);
isLoading = false;
setState(() { });
});
}
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);
});
}