Saving a value as a string with Flutter Firestore Firebase - firebase

I want to save a value from my Cloud Firestore as a string. I am using Flutter with Dart. I have been able to save it when building the page using MaterialepageRoute:
MaterialPageRoute(
builder: (context) => MainScreen(
currentUserId: firebaseUser.uid,
currentUserGender: document['gender'],
currentUserPreference: document['preference'],
)),
But this isn't an option with all of my pages, so I have to look for something else. I want to get the value from my Firestore Database, and then save it as a string, since I want to:
if (currentUserGender == 'male') {
//then do something
}
I have no idea how to do this, I have thought about using a Class, maybe the "get"-function with Firebase, but none have worked. I am not really sure how to do this, so any help is appreciated. I am able to get the currentUser. Here is a picture of my database:
https://imgur.com/KL7HX6P
Thanks in advance.

A Minimal Example: To fetch a Single Document Fields. Swap Collection & Document name in the code with your Own Names.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class GetUser extends StatefulWidget {
#override
_GetUserState createState() => _GetUserState();
}
class _GetUserState extends State<GetUser> {
Map<String, dynamic> userDetails = {};
Future<Null> getUser() async {
await Firestore.instance
.collection('users') // Your Collections Name
.document('eMAE4XF9cTYS12MpfOuWBW4P2WH3') // Your user Document Name
.get()
.then((val) {
userDetails.addAll(val.data);
}).whenComplete(() {
print('Data Fetched');
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RaisedButton(
textColor: Colors.white,
color: Theme.of(context).accentColor,
onPressed: () async {
await getUser();
},
child: Text('Get User Detail from Cloud'),
),
userDetails.length > 0
? Column(
children: <Widget>[
Text('${userDetails['gender']}'),
Text('${userDetails['id']}'),
Text('${userDetails['nickname']}'),
userDetails['gender'] == 'male'
? Text('Its Boy')
: Text('Girl'),
],
)
: Text('No user Data, Please Fetch'),
],
),
),
);
}
}

Related

Incorrect use of parent Widget

I am trying to make a flash Chat App that retrieves the chats from fireBase and displays it on the Screen .I have wrapped it under an Expanded widget .I have give some padding to it .
I am getting the following error
The following assertion was thrown while looking for parent data.:
Incorrect use of ParentDataWidget.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flashchat1/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ChatScreen extends StatefulWidget {
static String id='Chat_Screen';
#override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final _fireStore = FirebaseFirestore.instance;//an instance of fireBase store that stored data created
final _auth = FirebaseAuth.instance;//instance/object of fireBase auth that authorizes users is created
late User loggedInUser;//LoggedInUser is of type FireBase user(now changed to user)
late String messageText;
#override
void initState()
{
super.initState();
getCurrentUser();//calling the getCurrentUser
}
void getCurrentUser()
async{
try
{
final user= await _auth.currentUser;//get the current user id/name/email.Also currentUser return a future so make it async by adding await and async keywords
if(user!=null)
{
loggedInUser=user ;//LoggedInUser = user contains email of the info
print(loggedInUser.email);
}
}
catch(e)
{
print(e);
}
}// Under collection there is documents.Inside documents there are fields like type ,values etc.These fields contain our information
Future<void> messageStream()//Using a stream it becomes very easy .U just need to click once after you run the app .Then u will be done.
async {//The snapShot here is FireBase's Query SnapShot
await for(var snapshot in _fireStore.collection('messages').snapshots()){//make a variable snapshot to store the entire items of the collection in fireBase (Look at the fireBase console there is a collection called messages).This collection takes the snapshot of all the iteams (not literal snapshot .Think it like a snapShot)
for(var message in snapshot.docs)//make a variable message to access the snapShot.docs .(docs stands for Documentation.Look at the fireBase console)
print(message.data());
}
}
void getMessages()//(The problem with this is that we need to keep clicking on the onPressed button every single time the new message is sent .So it is not convinient
async {
final messages = await _fireStore.collection('messages').get();//to retrieve the data from fire base we are creating a variable message
messages.docs;//retreive the data from document section under the collection in firestore
for(var message in messages.docs)//since it is a messages.docs is a list we need to loop through it
{
print(message.data());//print the data its messge.data()
}
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
messageStream();
//_auth.signOut();
//Navigator.pop(context);
//Implement logout functionality
}),
],
title: Text('⚡️Chat'),
backgroundColor: Colors.lightBlueAccent,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: StreamBuilder(
stream:_fireStore.collection('messages').snapshots(),
builder: (context, AsyncSnapshot snapshot) {
//This is Flutter's Async snapShot
//if(!snapshot.data)
// {
// return Center(
//child: CircularProgressIndicator(
//backgroundColor:Colors.lightBlueAccent,
//),
//);
//}
if(!snapshot.hasData){//flutters async snapshot contains a query snapshot
return Center(
child:CircularProgressIndicator(
backgroundColor:Colors.lightBlueAccent,
),
);
}
final messages = snapshot.data.docs;
List<Text> messageWidgets = [];
for(var message in messages)//Loop through the messages
{
final messageText = message.data()['text'];//retrieve the data under the text field in message collection
final messageSender = message.data()['Sender'];//retrieve the data under the Sender field in message collection
final messageWidget = Text('$messageText from $messageSender',
style:TextStyle(
fontSize:50,
),
);
messageWidgets.add(messageWidget);//add the text to the List messageWidget
}
return Expanded(
flex:2,
child: ListView(//changed from Column to ListView as we want to scroll down .Or else only finite messages can be fit
children: messageWidgets, //if u don't write else with a return it will show an error as null returned and null safety broken
padding: EdgeInsets.symmetric(horizontal: 5,vertical: 5),
),
);
},
),
),
Container(
decoration: kMessageContainerDecoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
onChanged: (value) {
messageText=value;//Whatever you chat will be stored in the variable String variable messageText
},
decoration: kMessageTextFieldDecoration,
),
),
FlatButton(
onPressed: () {
_fireStore.collection('messages').add({
'text': messageText,//add the messages sent to fireStore under the messages object that we created manually
'Sender': loggedInUser.email,//add the current users email to the sender field
},);
},//goal is to send the data that we type here to the fireStore cloud
child: Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}
return Expanded(
flex:2,
child: ListView(//changed from Column to ListView as we want to scroll down .Or else only finite messages can be fit
children: messageWidgets, //if u don't write else with a return it will show an error as null returned and null safety broken
padding: EdgeInsets.symmetric(horizontal: 5,vertical: 5),
),
);
This code block is the issue here. You cannot use Expanded widget anywhere you like. The Expanded widget can only be used inside Row or Column Widget.
Remove the Expanded widget in the above code block. It will works.

Error while retrieving data from FireBase into flutter project

I am working with Flutter sdk version 2.12.0.I am creating a chat app which can be used to chat with other users. The chat history will be stored in fireBase . I am trying to retrieve the data of what I chatted and display it on the screen using Stream Builder widget.
As i keep chatting the data should get automatically added.
I am getting the following error:
Closure call with mismatched arguments: function '[]'
Receiver: Closure: () => Map<String, dynamic> from Function 'data':.
Tried calling: []("text")
Found: []() => Map<String, dynamic>
I am not able to figure out which function has mis Matched arguments. Can you please me with it. Here is my code:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flashchat1/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ChatScreen extends StatefulWidget {
static String id='Chat_Screen';
#override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final _fireStore = FirebaseFirestore.instance;//an instance of fireBase store that stored data created
final _auth = FirebaseAuth.instance;//instance/object of fireBase auth that authorizes users is created
late User loggedInUser;//LoggedInUser is of type FireBase user(now changed to user)
late String messageText;
#override
void initState()
{
super.initState();
getCurrentUser();//calling the getCurrentUser
}
void getCurrentUser()
async{
try
{
final user= await _auth.currentUser;//get the current user id/name/email.Also currentUser return a future so make it async by adding await and async keywords
if(user!=null)
{
loggedInUser=user ;//LoggedInUser = user contains email of the info
print(loggedInUser.email);
}
}
catch(e)
{
print(e);
}
}// Under collection there is documents.Inside documents there are fields like type ,values etc.These fields contain our information
Future<void> messageStream()//Using a stream it becomes very easy .U just need to click once after you run the app .Then u will be done.
async {//The snapShot here is FireBase's Query SnapShot
await for(var snapshot in _fireStore.collection('messages').snapshots()){//make a variable snapshot to store the entire items of the collection in fireBase (Look at the fireBase console there is a collection called messages).This collection takes the snapshot of all the iteams (not literal snapshot .Think it like a snapShot)
for(var message in snapshot.docs)//make a variable message to access the snapShot.docs .(docs stands for Documentation.Look at the fireBase console)
print(message.data());
}
}
void getMessages()//(The problem with this is that we need to keep clicking on the onPressed button every single time the new message is sent .So it is not convinient
async {
final messages = await _fireStore.collection('messages').get();//to retrieve the data from fire base we are creating a variable message
messages.docs;//retreive the data from document section under the collection in firestore
for(var message in messages.docs)//since it is a messages.docs is a list we need to loop through it
{
print(message.data());//print the data its messge.data()
}
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
messageStream();
//_auth.signOut();
//Navigator.pop(context);
//Implement logout functionality
}),
],
title: Text('⚡️Chat'),
backgroundColor: Colors.lightBlueAccent,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: StreamBuilder(
stream:_fireStore.collection('messages').snapshots(),
builder: (context, AsyncSnapshot snapshot) {
//This is Flutter's Async snapShot
//if(!snapshot.data)
// {
// return Center(
//child: CircularProgressIndicator(
//backgroundColor:Colors.lightBlueAccent,
//),
//);
//}
if(snapshot.hasData){//flutters async snapshot contains a query snapshot
final messages = snapshot.data.docs;
List<Text> messageWidgets = [];
for(var message in messages)//Loop through the messages
{
final messageText = message.data['text'];//retrieve the data under the text field in message collection
final messageSender = message.data['Sender'];//retrieve the data under the Sender field in message collection
final messageWidget = Text('$messageText from $messageSender');
messageWidgets.add(messageWidget);//add the text to the List messageWidget
}
return Column(//
children: messageWidgets,//if u don't write else with a return it will show an error as null returned and null safety broken
);
}
else{
return Column();
}
},
),
),
Container(
decoration: kMessageContainerDecoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
onChanged: (value) {
messageText=value;//Whatever you chat will be stored in the variable String variable messageText
},
decoration: kMessageTextFieldDecoration,
),
),
FlatButton(
onPressed: () {
_fireStore.collection('messages').add({
'text': messageText,//add the messages sent to fireStore under the messages object that we created manually
'Sender': loggedInUser.email,//add the current users email to the sender field
},);
},//goal is to send the data that we type here to the fireStore cloud
child: Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}
Change this:
final messageText = message.data['text'];
final messageSender = message.data['Sender'];
into this:
final messageText = message.data()['text'];
final messageSender = message.data()['Sender'];

Flutter display user information using firebase auth

I would like to display the uid and email from Firebase Auth (just used for auth only!) in my Drawer.
I have this method to return the uid :
static Future<String> getUID() async {
User? user = await FirebaseAuth.instance.currentUser;
return user!.uid;
}
And this is my Drawer :
class DrawerMenu extends StatefulWidget {
final String pageName;
const DrawerMenu({Key? key, required this.pageName}) : super(key: key);
#override
_DrawerMenuState createState() => _DrawerMenuState();
}
class _DrawerMenuState extends State<DrawerMenu> {
#override
Widget build(BuildContext context) {
// print(MaterialLocalizations.of(context));
return Scaffold(
appBar: AppBar(title: Text('Title')),
body: Center(
child: DashboardPage(),
),
drawer: Drawer(
child: ListView(padding: EdgeInsets.all(0.0), children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text(LoginPageService.getUID().toString()), // HERE HERE HERE HERE
accountEmail: Text('random#gmail.com'),
currentAccountPicture: CircleAvatar(
backgroundImage: ExactAssetImage('assets/random.jpg'),
),
otherAccountsPictures: <Widget>[
CircleAvatar(
child: Text('A'),
backgroundColor: Colors.white60,
),
CircleAvatar(
child: Text('R'),
),
],
onDetailsPressed: () {},
...
...
...
I know that LoginPageService.getUID() will return a Future, so yes it should not be used like that.
But i don't know what's the best way for doing it and where to put the code.. in the widget ? or elsewhere ?
Should i use .then((value).... to get the uid..
Let me know if you have experience with it, and how you did it
Thanks for any help !
To complete the answer of #Youri you can do this :
static Future<User?> getCurrentUser() async {
return await auth.currentUser;
}
And in your drawer :
String? uid, name;
#override
void initState() {
super.initState();
LoginPageService.getCurrentUser().then((user) {
setState(() {
uid = user?.uid;
email = user?.email;
});
});
}
And then you can use it like that :
accountName: Text(name.toString()),
You could make use of the FutureBuilder for any async code. This widget automatically rebuilds whenever the status of the provided Future changes.
Please checkout this widget of the week video from Flutter for more information on this Widget.
FutureBuilder (Flutter Widget of the Week)

Not able to fetch particular user document by user id in flutter app

I want to retrieve a particular user document by its id from the collection users. When I directly pass the particular user id, I get the data. But when I pass it using variable it shows null.
My code is as follows:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../services/crud.dart';
class test extends StatefulWidget {
#override
_testState createState() => _testState();
}
class _testState extends State<test> {
String userID="";
#override
void initState() {
super.initState();
///get current user and assign his id
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() {
userID = user.uid;
print(userID);
});
});
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
StreamBuilder(
stream: Firestore.instance.collection('users').document(userID).snapshots(),
builder: (context,snapshot){
if (!snapshot.hasData) return const Text("Loading...");
else return Container(
child: Column(
children: <Widget>[
Text(snapshot.data["name"]),
Text(snapshot.data["email"]),
Text(snapshot.data["phone"].toString()),
],
),
);
},
)
],
)
);
}
}
When I'm using the following line of code with specifying uid it shows the result :
stream: Firestore.instance.collection('users').document('d6DshRomJMkIe9mAARAi').snapshots(),
But it does not work when I pass userID inside the document(). Even though userID contains the actual id of the logged-in user.
stream: Firestore.instance.collection('users').document(userID).snapshots(),
The error says :
NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling []("name")
This is the structure of my database.
This is the error that I get on my app screen.
When using userID is doesn't work because currentUser() is asynchronous and the StreamBuilder is being called even before getting the userId therefore try the following:
Stream<DocumentSnapshot> getData()async*{
FirebaseUser user = await FirebaseAuth.instance.currentUser();
yield* Firestore.instance.collection('users').document(user.uid).snapshots();
}
Create a method that returns a Stream and then inside the StreamBuilder do the following:
children: <Widget>[
StreamBuilder(
stream: getData(),
builder: (context,snapshot){
if (!snapshot.hasData) return const Text("Loading...");
else if(snapshot.hasData){
return Container(
child: Column(
children: <Widget>[
Text(snapshot.data["name"]),
Text(snapshot.data["email"]),
Text(snapshot.data["phone"].toString()),
],
),
);
},
return CircularProgressIndicator();
},
)
],

Flutter Firebase RealTime Databasee not ordering properly with OrderByChild() [duplicate]

This question already has an answer here:
Flutter: Firebase Real-Time database orderByChild has no impact on query result
(1 answer)
Closed 2 years ago.
I'm creating a simple application with Firebase Realtime database where a user inputs a text and it gets added to a list of chats.
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _firebaseRef = FirebaseDatabase().reference().child('chats');
TextEditingController _txtCtrl = TextEditingController();
#override
Widget build(BuildContext context) {
var comments = _firebaseRef.orderByChild('time').limitToLast(10);
return Scaffold(
body: Container(
child: SafeArea(
child: Column(
children: <Widget>[
Container(
child: Row(children: <Widget>[
Expanded(child: TextField(controller: _txtCtrl)),
SizedBox(
width: 80,
child: OutlineButton(
child: Text("Add"),
onPressed: () {
sendMessage();
}))
])),
StreamBuilder(
stream: comments.onValue,
builder: (context, snap) {
if (snap.hasData &&
!snap.hasError &&
snap.data.snapshot.value != null) {
Map data = snap.data.snapshot.value;
List item = [];
data.forEach(
(index, data) => item.add({"key": index, ...data}));
return Expanded(
child: ListView.builder(
itemCount: item.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(item[index]['message']),
);
},
),
);
} else
return Center(child: Text("No data"));
},
),
],
),
),
),
);
}
sendMessage() {
_firebaseRef.push().set({
"message": _txtCtrl.text,
'time': DateTime.now().millisecondsSinceEpoch
});
}
}
It stores and retrieves data perfectly. But when I try adding data, the new items are placed at random points in the list.
For example, in the image below, the last item I placed into the list was 'Nine'. But it was put in the center of the list:
I've tried sorting the list by timestamps, but it did nothing.
What could be causing this issue? And how can I fix it?
When you call snap.data.snapshot.value; the data in the snapshot (which is ordered) is converted to a Map<String, Object> which isn't ordered. To maintain the order, you'll want to listen to onChild... instead.
Note that FlutterFire has a convenient firebase_list library that handles most of the heavy lifting of onChild... for you.
Also see:
Flutter Firebase Database wrong timestamp order
Flutter sort Firebase snapshot by timestamp
Flutter: Firebase Real-Time database orderByChild has no impact on query result
This might work:
use a Query
Query comments = _firebaseRef.orderByChild('time').limitToLast(10);

Resources