How to sync Firestore database and Firebase Authentication - firebase

I'm trying to create a simple banking app with flutter.I'm creating the user login information myself and trying to auth them with firebase. I already coded the authentication part of the app.Here is the code:
import 'package:banking_app_firebase/screens/customers_info.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import '../constants.dart';
class LoginScreen extends StatefulWidget {
static const String id = 'login_screen';
const LoginScreen({Key? key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _auth = FirebaseAuth.instance;
bool showSpinner = false;
String? email;
String? password;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Flexible(
child: Hero(
tag: 'logo',
child: Container(
height: 100,
child: Image.network(
"https://image.flaticon.com/icons/png/512/662/662622.png",
),
),
),
),
SizedBox(height: 20),
TextField(
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
onChanged: (value) {
email = value;
},
decoration:
kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
),
SizedBox(
height: 20,
),
TextField(
obscureText: true,
textAlign: TextAlign.center,
onChanged: (value) {
password = value;
},
decoration: kTextFieldDecoration.copyWith(
hintText: "Enter your password"),
),
SizedBox(
height: 24,
),
Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Material(
elevation: 5,
color: Colors.white,
borderRadius: BorderRadius.circular(30),
child: MaterialButton(
onPressed: () async {
setState(() {
showSpinner = true;
});
try {
final user = await _auth.signInWithEmailAndPassword(
email: email!, password: password!);
if (user != null) {
Navigator.pushNamed(context, CustomerScreen.id);
}
setState(() {
showSpinner = true;
});
} catch (e) {
print(e);
}
},
height: 42,
child: Text(
"Login",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
),
],
),
),
),
);
;
}
}
Sample Users:
However, I don't know how to sync these information with my database so I can reach the data in the database. Here is my example database:
How can I get the informations about customers like name,surname,balance after auth is successful? I mean, how can I tell the Firebase, the auth email and password same as firestore database?

How can I get the information about customers like
name, surname, balance after auth is successful?
I understand that you want to link one document of the customers collection to each user. The classical solution to do so is to use the user uid as the Firestore document ID.
As soon as your user is created, you can get its uid and create the Firestore document, like, for example:
final user = await _auth.signInWithEmailAndPassword(
email: email!, password: password!
);
if (user != null) {
await addCustomer(user.uid, email, password);
Navigator.pushNamed(context, CustomerScreen.id);
}
...
CollectionReference customers = FirebaseFirestore.instance.collection('customers');
Future<void> addCustomer(userID, email, password) {
return customers
.doc(userID)
.set({
...
})
.then((value) => print("Customer added"))
.catchError((error) => print("Failed to add customer: $error"));
}
I understand from your comment below that you want to query the customers collection to find the user which has a specific email and password.
This is possible with a query, however I would recommend not using the password value for executing queries. This is a sensitive data that you should avoid using as a query parameter.
Actually you can very well query just by email: since you cannot create two Firebase users with the same email, you are sure that your query will return a unique result (if you didn't create some duplicate documents in the customers collection...).

Related

The function can't be unconditionally invoked because it can be 'null' error shown while trying to get current user info from firebase Auth

Trying to get current user info after creating a new user but getting this error " The function can't be unconditionally invoked because it can be 'null' " while trying to invoke ".currentUser()" method how to fix this?
here is the code the error occurs when trying to call " final user=await _auth.currentUser();"
enter code here
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class RegistrationScreen extends StatefulWidget {
#override
_RegistrationScreenState createState() => _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
final _auth =FirebaseAuth.instance;
late String eMail;
late String password;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
height: 200.0,
child: Image.asset('images/logo.png'),
),
SizedBox(
height: 48.0,
),
TextField(
onChanged: (value) {
//Do something with the user input.
eMail=value;
},
),
SizedBox(
height: 8.0,
),
TextField(
onChanged: (value) {
//Do something with the user input.
password=value;
},
),
SizedBox(
height: 24.0,
),
Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
color: Colors.blueAccent,
borderRadius: BorderRadius.all(Radius.circular(30.0)),
elevation: 5.0,
child: MaterialButton(
onPressed: () async {
try{
final _newUser= await _auth.createUserWithEmailAndPassword(email: eMail, password: password);
if(_newUser!=null)
{
final user=await _auth.currentUser();
}
}
catch(e)
{
print(e);
}
},
minWidth: 200.0,
height: 42.0,
child: Text(
'Register',
style: TextStyle(color: Colors.white),
),
),
),
),
],
),
),
);
}
}
solved it the problem was i was calling "final user =_auth.currentUser()" function which had been changed to "final user =_auth.currentUser" currentUser was a getter and also no need of await keyword and to get email ,uid etc from user we should check
if user is null then acess email and uid etc.
enter code here
final _newUser= await _auth.createUserWithEmailAndPassword(email: eMail, password: password);
if(_newUser!=null)
{
final user =_auth.currentUser;
if(user!=null)
{
final email = user.email;
print(email);
}
}
As the error says, you should add a null check as below:
filan user = await _auth!.currentUser();
Because _auth can be null. Also you can use this code:
filan user = await _auth?.currentUser() ?? User(); // the name of user class

Flutter: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
Where create call Firebase.initializeApp() ?
what should I change in my code? Is there any way to do it? In case you want to see the code please let me know I will update more.
auth.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:quiz2/model/user.dart';
class AuthService {
FirebaseAuth _auth = FirebaseAuth.instance;
UserFire _userFromFirebase(User user){
return user != null ? UserFire(uid: user.uid):null;
}
Future signInEmailAndPass(String email, String password) async {
try {
UserCredential authResult = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User firebaseUser = authResult.user;
return _userFromFirebase(firebaseUser);
} catch (e) {
print(e.toString());
}
}
Future signUpWithEmailAndPassword(String email, String password) async{
try{
UserCredential authResult = await _auth.createUserWithEmailAndPassword(email: email, password: password);
User firebaseUser = authResult.user;
return _userFromFirebase(firebaseUser);
}catch(e){
print(e.toString());
}
}
Future signOut() async{
try{
return await _auth.signOut();
}catch(e){
print(e.toString());
return null;
}
}
}
signup.dart
import 'package:flutter/material.dart';
import 'package:quiz2/database/auth.dart';
import 'package:quiz2/screens/landing.dart';
import 'package:quiz2/screens/signin.dart';
import 'package:quiz2/widgets/widget.dart';
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _formKey = GlobalKey<FormState>();
String email, password, name;
AuthService authService = new AuthService();
bool _isLoading = false;
signUp() async {
if (_formKey.currentState.validate()) {
setState(() {
_isLoading = true;
});
authService.signUpWithEmailAndPassword(email, password).then((val) {
if (val != null) {
setState(() {
_isLoading = false;
});
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => MyHomePage()));
}
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: appBar(context),
backgroundColor: Colors.transparent,
elevation: 0.0,
brightness: Brightness.light,
),
body: _isLoading
? Container(child: Center(child: CircularProgressIndicator()))
: Form(
key: _formKey,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(
children: [
Spacer(),
TextFormField(
validator: (val) {
return val.isEmpty ? 'Enter Name' : null;
},
decoration: InputDecoration(hintText: 'Name'),
onChanged: (val) {
name = val;
},
),
SizedBox(
height: 6,
),
TextFormField(
validator: (val) {
return val.isEmpty ? 'Enter Email' : null;
},
decoration: InputDecoration(hintText: 'Email'),
onChanged: (val) {
email = val;
},
),
SizedBox(
height: 6,
),
TextFormField(
obscureText: true,
validator: (val) {
return val.isEmpty ? 'Enter password' : null;
},
decoration: InputDecoration(hintText: 'Password'),
onChanged: (val) {
password = val;
},
),
SizedBox(
height: 24,
),
GestureDetector(
onTap: () {
signUp();
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 16),
decoration: BoxDecoration(
color: Colors.teal,
borderRadius: BorderRadius.circular(30)),
alignment: Alignment.center,
width: MediaQuery.of(context).size.width - 48,
child: Text(
"Sign Up",
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
SizedBox(
height: 18,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Alredy have an account?",
style: TextStyle(fontSize: 16),
),
GestureDetector(
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => SignIn()));
},
child: Text(" Sign In",
style: TextStyle(
fontSize: 16,
decoration: TextDecoration.underline)))
],
),
SizedBox(
height: 80,
),
],
)),
),
);
}
}
user.dart
class UserFire{
String uid;
UserFire({this.uid});
}
what should I change in my code? Is there any way to do it? In case you want to see the code please let me know I will update more.
You need initialize your firebase .Do as follows:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Did you complete all the installation steps?
if you answer is yes :
you must check this link

How do i catch error of authentication while logging in and signup using firebase and flutter?

I am pretty new to flutter and this is my first project in which i am using backend like firebase.
So i pre build an ui and started to integrate firebase in it it was successfully done and it is working as accepted but when i am trying to print out the errors while logging in signup i am failing to do that, i am able to catch the errors in my console but i wait to update my users with that error text.
when ever i am trying to log in though i am providing a wrong password it is taking me to the home page which i dont want
This is my Log In page with a pre build ui and with working setup of log in
import 'package:flutter/material.dart';
import 'package:notepad/Authentigation%20Screens/signUp.dart';
import 'package:notepad/animation/bouncypagetrans.dart';
import 'package:notepad/animation/fadeanimation.dart';
import 'package:notepad/auth/authMethod.dart';
import 'package:notepad/screens/homepage.dart';
import 'package:notepad/widgets/VxTextsHeaders.dart';
import 'package:notepad/widgets/customRaisedButton.dart';
import 'package:notepad/widgets/loading.dart';
import 'package:notepad/widgets/textformField.dart';
import 'ForgotPassword.dart';
class LogIn extends StatefulWidget {
#override
_LogInState createState() => _LogInState();
}
class _LogInState extends State<LogIn> {
String error;
AuthMethods authMethods = new AuthMethods();
bool isLoading = false;
final formKey = GlobalKey<FormState>();
TextEditingController emailTextEditingController =
new TextEditingController();
TextEditingController passwordTextEditingController =
new TextEditingController();
logMein() {
if (formKey.currentState.validate()) {
try {
setState(() {
isLoading = true;
});
authMethods
.signInWithEmailAndPassword(emailTextEditingController.text,
passwordTextEditingController.text)
.then((val) {
// print("${val.uId}");
Navigator.pushReplacement(
context,
BouncyPageRout(
widget: HomePage(),
),
);
});
} catch (e) {
setState(() {
error = e.message;
});
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: true,
body: isLoading
? Loading()
: SafeArea(
child: Container(
width: double.infinity,
padding: EdgeInsets.fromLTRB(30.0, 100.0, 30.0, 20.0),
height: MediaQuery.of(context).size.height,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FadeAnimation(
1.0,
headerTitle("Hello,"),
),
FadeAnimation(
2.0,
headerSubTitle("Log in to continue"),
),
],
),
SizedBox(height: 65),
Column(
children: [
Form(
key: formKey,
child: Column(children: [
SizedBox(height: 20),
FadeAnimation(
3.0,
buildTextField(
validator: (val) {
return val.isEmpty ||
RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(val)
? null
: "Please provide a valid Email";
},
labelText: "Email",
controller: emailTextEditingController),
),
SizedBox(height: 20),
FadeAnimation(
3.5,
buildTextField(
validator: (val) {
return val.isEmpty || val.length < 6
? "Please Provide a Strong Password,/n Provide somthing greater than 6 "
: null;
},
labelText: "Password",
obscureText: true,
controller:
passwordTextEditingController),
),
])),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerRight,
child: FadeAnimation(
4.0,
InkWell(
onTap: () {
Navigator.push(
context,
BouncyPageRout(
widget: ForgotPassword(),
),
);
},
child: Text(
'Forgot Password?',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.deepOrange,
fontSize: 14),
),
),
),
),
SizedBox(height: 40),
FadeAnimation(
4.5,
raisedButton(
context: context,
onPressed: () {
logMein();
},
color: Colors.deepOrange,
title: "Log In",
textColor: Colors.white,
),
),
SizedBox(
height: 20.0,
),
FadeAnimation(
5.0,
raisedButton(
context: context,
onPressed: () {
Navigator.push(
context,
BouncyPageRout(
widget: SignUp(),
),
);
},
color: Colors.white,
title: "SignUp"),
),
],
)
],
),
),
),
),
);
}
}
AuthMethods page with contains all the codes of firebase
import 'package:notepad/auth/user.dart';
class AuthMethods {
String error;
final FirebaseAuth _auth = FirebaseAuth.instance;
User _userFromFirebaseUser(FirebaseUser user) {
return user != null ? User(userId: user.uid) : null;
}
Future signInWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.signInWithEmailAndPassword(
email: email, password: password);
FirebaseUser firebaseUser = result.user;
return _userFromFirebaseUser(firebaseUser);
} catch (e) {
print(e.toString());
}
}
Future signUpwithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
FirebaseUser firebaseUser = result.user;
return _userFromFirebaseUser(firebaseUser);
} catch (e) {
print(e.toString());
}
}
Future resetPass(String email) async {
try {
return await _auth.sendPasswordResetEmail(email: email);
} catch (e) {
print(e.toString());
}
}
Future signOut() async {
try {
return await _auth.signOut();
} catch (e) {
print(e.toString());
}
}
}
so basically i want to notify my users a valid error message and untill they solve that they should not navigate to a perticular screen
You can use a snackbar widget and call them in your throw function! Follow this link to learn more about snackbars
https://flutter.dev/docs/cookbook/design/snackbars

Need help in accessing current user's information from cloud firestore and include the information in my application

This is where i want to access and include users logged in user's data from firestore
class CategorySelector extends StatefulWidget {
#override
_CategorySelectorState createState() => _CategorySelectorState();
}
class _CategorySelectorState extends State<CategorySelector> {
Future<Widget> _getImage(BuildContext context, String imageName) async{
Image image;
await FireStorageService.loadImage(context,imageName).then((value){
image = Image.network(value.toString(),
fit: BoxFit.cover,
);
});
return image;
}
#override
Widget build(BuildContext context) {
return Container(
height: 100.0,
width: double.infinity,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
width: 80.0,
height: 80.0,
margin: EdgeInsets.only(left: 10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
boxShadow: [
BoxShadow(
//color: Color.fromRGBO(143, 148, 251, .2),
color: Colors.black12,
blurRadius: 5.0,
offset: Offset(8, 8)
)
]
),
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: FutureBuilder(
future: _getImage(context,"Screenshot_2020-12-12-07-27-13-73.png"),
builder: (context, snapshot){
//if(snapshot.connectionState == ConnectionState.done){
return Container(
width: 80.0,
height: 80.0,
child: snapshot.data,
);
//}
},
),
/*child: Image(
image: AssetImage(user.imageUrl),
),*/
),),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Welcome,',
style: TextStyle(
fontFamily: 'Roboto',
color: Colors.grey,
fontSize: 20.0,
),),
Text('hi',
style: TextStyle(
fontFamily: 'Roboto',
color: Colors.black54,
fontSize: 20.0,
fontWeight: FontWeight.bold,
),),
],
),
Container(
margin: EdgeInsets.only(right: 10.0),
width: 80.0,
height: 80.0,
child: Image(
image: AssetImage('assets/images/logo.png'),
),),
],
),
);
}
}
class FireStorageService extends ChangeNotifier{
FireStorageService();
static Future<dynamic> loadImage(BuildContext context, String image) async {
return await FirebaseStorage.instance.ref().child(image).getDownloadURL();
}
}
I created this class for user authentication
class AuthenticationService {
final FirebaseAuth _auth = FirebaseAuth.instance;
//user registration with email and password
Future<User> createNewUser(String email, String password, String imageUrl) async {
try{
UserCredential result = await _auth
.createUserWithEmailAndPassword(email: email, password: password);
User user = result.user;
print('auth ser $imageUrl');
if(user != null) {
await DatabaseManager().createUserData(user.email, imageUrl, user.uid);
return user;
}
return null;
}catch(e){
return null;
}
}
//user sign in with email and password
Future loginUser(String email, String password) async {
try{
UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
return result.user;
}catch(e){
print(e.toString());
return null;
}
}
*//i think this function will help me to access current user's information, but it did not help*
Future<User> getCurrentUser()async{
User user = _auth.currentUser;
return user;
}
}
this is where i included all database operations.
class DatabaseManager {
final CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> createUserData( String email,String imageUrl, String uid) async{
return await users.doc(uid).set({
'id': uid,
'email': email,
'user_name': email.substring(0,email.lastIndexOf("#")),
'img_url': imageUrl
});
}
}
this is my user model
import 'package:flutter/foundation.dart';
class User {
int id;
String name;
String email;
String imageUrl;
String password;
User({
#required this.id,
#required this.name,
#required this.imageUrl,
#required this.email,
#required this.password,
});
User.fromMap(Map<String, dynamic> json){
this.id = json['id'];
this.name = json['name'];
this.imageUrl = json['img_url'];
this.email = json['email'];
this.password = json['password'];
}
}
i really don't know how to retrieve the logged in user's information from firebase. I want to access the image stored in firebase storage and user's name from firestore and display in my app through class categorySelector. Help will be appreciated a lot. This is how i have structured the users collection.
If you use Firebase Auth you can access simple data like name, email, and phone number, etc, you can use
FirebaseAuth.instance.currentUser
else if you want to access the data in Firestore I suggest you read the documentation and learn it yourself instead of getting a one-time code of how to do it.

Flutter: CRUD clarifications over Firebase

I've been working on a little project on flutter since I just started learning it a week ago and I'm just wondering how I could retrieve a specific snippet of data from Firebase's Firestore database.
Here is the code on the relevant files:
database.dart
import 'package:plannus/models/user.dart';
class DatabaseMethods {
final String uid;
DatabaseMethods({this.uid});
final CollectionReference users = Firestore.instance.collection("users");
Future<void> updateUserData(String name, String handle) async {
print(uid);
return await users.document(uid).updateData({
'name' : name,
'handle' : handle,
});
}
Future<void> updateSpecificUserData(String uid, String name, String handle) async {
print(uid);
return await users.document(uid).updateData({
'name' : name,
'handle' : handle,
});
}
Future<Set<Set<String>>> getUserData() {
return users.document(uid).get().then((value) => {
if (value.exists) {
value.data['handle']
}
});
}
void getSpecificUserData(String uid, String capture) async {
DocumentSnapshot snapshot = await users.document(uid).get();
capture = snapshot.data['handle'];
print(capture);
}
Future<String> retrieveData(String uid) async {
DocumentSnapshot snap = await users.document(uid).get();
Map<String, String> map = snap.data;
String handle = map['name'];
return handle;
}
//
uploadUserInfo(userMap) {
Firestore.instance.collection("users").add(userMap);
}
// user data from snapshot
Stream<QuerySnapshot> get userInfo {
return users.snapshots();
}
}
profile.dart
import 'package:flutter/material.dart';
import 'package:plannus/messages/database.dart';
import 'package:plannus/models/user.dart';
import 'package:plannus/services/auth.dart';
import 'package:provider/provider.dart';
class Profile extends StatefulWidget {
#override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
final AuthService auth = AuthService();
final formKey = GlobalKey<FormState>(); // 'id' of form
bool loading = false;
// text field state
String name = '';
String password = '';
String handle = '';
String error = '';
DatabaseMethods databaseMethods = new DatabaseMethods();
QuerySnapshot currentUser;
#override
Widget build(BuildContext context) {
User user = Provider.of<User>(context);
String handle = '';
print(user.uid);
Future<String> str = databaseMethods.retrieveData(user.uid);
str.then((value) => {
handle = value
});
print(handle);
return new Scaffold(
// appBar: AppBar(
// title:
// ),
body: Container(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 50),
child: Form(
key: formKey, // keep track of form and its state
child : Column (
children: <Widget>[
Image.asset('assets/profilepicture.png', height: 300, width: 300),
SizedBox(height: 20),
TextFormField(
decoration: InputDecoration(
hintText: 'Name',
icon: Icon(Icons.person_outline, color: Colors.blue),
fillColor: Colors.white,
filled: true,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey[300], width: 2),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2),
)
),
validator: (val) => val.isEmpty ? 'Enter your name' : null,
onChanged: (val) {
setState(() => name = val);
},
),
SizedBox(height: 20),
TextFormField(
decoration: InputDecoration(
hintText: 'Handle',
icon: Icon(Icons.alternate_email, color: Colors.blue),
fillColor: Colors.white,
filled: true,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey[300], width: 2),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2),
)
),
obscureText: false,
validator: (val) => val[0] != '#' ? 'Handle starts with #!' : null,
onChanged: (val) {
setState(() => handle = val);
},
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget> [
RaisedButton(
color: Colors.blueAccent,
child: Text(
'Update',
style: TextStyle(color: Colors.white),
),
onPressed: () async {
if(formKey.currentState.validate()) {
print(user.uid);
await databaseMethods.updateSpecificUserData(user.uid, name, handle);
setState(() {
error = 'Update successful!';
});
}
},
),
],
),
SizedBox(height: 12),
Text(
error,
style: TextStyle(color: Colors.black, fontSize: 16),
)
],
),
),
),
);
}
}
My code can be real messy (for which I apologise because I have been stuck on this for a quite long time and have been rigorously attempting various methods to extract the data out).
Ultimately, my main objective is to get the value(handle) from my data stored in firebase and then to dynamically display it on my appbar.
My firebase database collection is named 'users' and carries only data { name: "...", handle: "..."}.
Thanks for bearing with my long post.
Profile page
Here is how you can get data from firebase's firestore. I think its best to rename your "name" as "n" to make the size of your data stored in the database smaller.
await Firestore.instance
.collection('users')
.document(uid)
.get()
.then((DocumentSnapshot ds) {
username = ds["name"];
});

Resources