fetch data from firebase firestore instead of constants - firebase

here in this code the data is being displayed from a constants file but i want to fetch it from firestore
what changes should i make to get data from firestore and also i dont want to fetch image from firestore
i want to fetch data from firebase firestore instance
Main.dart
List<Widget> itemsData = [];
void getPostsData() {
List<dynamic> responseList = FOOD_DATA;
List<Widget> listItems = [];
responseList.forEach((post) {
listItems.add(Container(
height: 150,
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20.0)), color: Colors.white, boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),
]),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
post["name"],
style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
),
Text(
post["brand"],
style: const TextStyle(fontSize: 17, color: Colors.grey),
),
SizedBox(
height: 10,
),
Text(
"\$ ${post["price"]}",
style: const TextStyle(fontSize: 25, color: Colors.black, fontWeight: FontWeight.bold),
)
],
),
Image.asset(
"assets/images/${post["image"]}",
height: double.infinity,
)
],
),
)));
});
setState(() {
itemsData = listItems;
});
}

Related

How to show 3 text widgets inside a list-view-builder?

Im trying to show a listviewbuilder with 3 text widgets. But the last text widget don't looks good. Heres how it looks
And heres my code
#override
Widget build(BuildContext context) {
final user = Provider.of<Userforid>(context);
if (nosuerfound == true) {
return ListView.builder(
itemCount: _resultsList.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
child: ListTile(
onTap: () {
DatbaseService.instance
.createorGetConversation(user.uid, _resultsList[index].id,
(String _conversationID) {
/* NavigationService.instance.navigateToRoute(
MaterialPageRoute(builder: (context) {
return MeineBeitraege(
_conversationID,
_resultsList[index].id,
_resultsList[index].data()['username'],
);
}),
);*/
});
},
leading: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Container(
child: Text(
_resultsList[index].data()['hashtag1'],
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20.0,
),
),
),
),
Expanded(
child: Container(
child: Text(
_resultsList[index].data()['hashtag2'],
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20.0,
),
),
),
),
Expanded(
child: Container(
child: Text(
_resultsList[index].data()['hashtag3'],
style: const TextStyle(
// fontWeight: FontWeight.w500,
fontSize: 20.0,
),
),
),
),
],
),
// subtitle: Text(_resultsList[index].data()['email']),
),
);
});
} else {
return Padding(
padding: const EdgeInsets.fromLTRB(0, 30, 0, 0),
child: Container(
child: Text(
"No Hashtag found",
style: TextStyle(fontSize: 16),
)),
);
}
}
}
So what I want is getting a bit padding between every text widget inside column. And also the last hashtag should be showed correctly . Not showed half .Hope anyone can help .if you need more informations please leave a comment .
You don't need use ListTile for show three elements in trailing, use custom widget or simple Container with Gesture Detector (or InkWell for the material tap effect).
It is not necessary either the Expanded Widget.
ListView.builder(
itemCount: _resultsList.length,
itemBuilder: (BuildContext context, int index) {
return Container(
padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
margin: const EdgeInsets.all(10.0), // Add margin
child: InkWell(
onTap: () {
/*DatbaseService.instance
.createorGetConversation(user.uid, _resultsList[index].id,
(String _conversationID) {
/* NavigationService.instance.navigateToRoute(
MaterialPageRoute(builder: (context) {
return MeineBeitraege(
_conversationID,
_resultsList[index].id,
_resultsList[index].data()['username'],
);
}),
);*/
});*/
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
_resultsList[index].data()['hashtag1'],
'Text 1',
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 15.0,
),
),
Text(
_resultsList[index].data()['hashtag2'],
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 15.0,
),
),
Text(
_resultsList[index].data()['hashtag3'],
style: const TextStyle(
// fontWeight: FontWeight.w500,
fontSize: 15.0,
),
),
],
),
),
);
},
),

flutter and firestore : change price and size dynamicly

hello iam using flutter and firebase in my project , i have a product and evert product have a price , every product have a list of sizes , i want the product to change its price when the size changes .
here is my product document :
i know that i have to change the prices into list but how to link them together in firebase or flutter .
this is my code :
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(0),
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: CustomText(
text: "Select a Size",
color: Colors.white,
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: DropdownButton<String>(
value: _size,
style: TextStyle(color: Colors.white),
items: widget.product.sizes
.map<DropdownMenuItem<String>>(
(value) => DropdownMenuItem(
value: value,
child: CustomText(
text: value,
color: Colors.red,
)))
.toList(),
onChanged: (value) {
setState(() {
_size = value;
});
}),
)
],
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"${widget.product.description}",
style: TextStyle(color: Colors.white)),
),
),
Padding(
padding: const EdgeInsets.all(9),
child: Material(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white,
elevation: 0.0,
child: MaterialButton(
onPressed: () async {
appProvider.changeIsLoading();
bool success = await userProvider.addToCart(
product: widget.product,
size: _size);
if (success) {
toast("Added to Cart!");
userProvider.reloadUserModel();
appProvider.changeIsLoading();
return;
} else {
toast("Not added to Cart!");
appProvider.changeIsLoading();
return;
}
},
minWidth: MediaQuery.of(context).size.width,
child: appProvider.isLoading
? Loading()
: Text(
"Add to cart",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
SizedBox(
height: 20,
)
],
),
),
)
],
There is trigger for widget :
onChanged: (value) {
setState(() {
_size = value;
reference.setData({quantity : value}, merge: true)
});
}),
Just change the reference to document path.

Adding a condition to retrieve certain data?

I want to add a conditional expression to the code so that the data that has the field 'category' entered as BS in firebase realtime database will be called and displayed. Here is a picture of the database table : https://imgur.com/a/PkdI71d
How do I add an expression to the following code so that only "English for Career Development" will be displayed and not "Excel Skills for Business" since "English for Career Development", or test 4 has a field category = 'bs' but test 5 doesn't so it will not show up.
Code:
class _BusinessPage1State extends State<BusinessPage1> {
List<AllCourses> coursesList = [];
#override
void initState(){
super.initState();
DatabaseReference referenceAllCourses = FirebaseDatabase.instance.reference().child('AllCourses');
referenceAllCourses.once().then(((DataSnapshot dataSnapshot){
coursesList.clear();
var keys = dataSnapshot.value.keys;
var values = dataSnapshot.value;
for(var key in keys){
AllCourses allCourses = new AllCourses(
values [key]["courseName"],
values [key]["teacher"],
values [key]["category"],
);
coursesList.add(allCourses);
}
setState(() {
//
});
}));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: ()
{Navigator.pop(context);
Navigator.push(context, MaterialPageRoute(builder: (context)=>homepage()));}),
title: Text("Creator's Club"),
backgroundColor: Color(0xff2657ce),
elevation: 0,),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Business', style: TextStyle(
color: Color(0xff2657ce),
fontSize: 27,
),),
Text('Choose which course you want to study.', style: TextStyle(
color: Colors.black.withOpacity(0.6),
fontSize: 20
),),
SizedBox(height: 10),
Expanded(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
coursesList.length == 0 ? Center(child: Text("Loading...", style: TextStyle(fontSize: 15),)): ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: coursesList.length,
itemBuilder: (_, index) {
return CardUI(coursesList[index].courseName, coursesList[index].teacher, coursesList[index].category);
}
)
]
),
),
),
]
)
)
);
}
}
Widget CardUI (String courseName, String teacher, String category){
return Card(
elevation: 1,
margin: EdgeInsets.all(5),
color: Color(0xffd3defa),
child: Container(
color: Colors.white,
margin: EdgeInsets.all(1),
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: Color(0xffd3defa),
borderRadius: BorderRadius.all(Radius.circular(17)),
),
child: IconButton(
icon: Icon(
Icons.star_border_rounded ,
color: Color(0xff2657ce),
),
),
),
SizedBox(width: 15,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: InkWell(
onTap: (){},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(courseName, style: TextStyle(fontSize: 18)),
SizedBox(height: 5),
Text(teacher, style: TextStyle(fontSize: 15, color: Colors.grey)),
SizedBox(height: 5),
Text(category, style: TextStyle(fontSize: 15)),
],
),
)
)
]
)
]
)
],
)
),
);
}
Code for 'AllCourses' :
class AllCourses {
String courseName;
String teacher;
String category;
AllCourses(this.courseName, this.teacher, this.category);
}
Just add a condition to check if the category is 'bs' before adding the course to the coursesList:
for(var key in keys){
AllCourses allCourses = new AllCourses(
values [key]["courseName"],
values [key]["teacher"],
values [key]["category"],
);
if(allCourses.get('category') == 'bs')
coursesList.add(allCourses);
}

Fetch user data from firestore and show them in profile screen using flutter

The issue here is that when I fetch the data, I am suppose to fetch it for the current user but it is rather fetching data for all users within that collection.
I have done reading and watched a number of videos for a possible solution but I can't seem to find how to do this. Your help is needed please. Thanks.
A excerpt of the bode is below.
File image;
TextEditingController loginNameController = TextEditingController();
TextEditingController loginPhoneController = TextEditingController();
TextEditingController loginAddressController = TextEditingController();
clearForm() {
setState(() {
image = null;
loginNameController.clear();
loginPhoneController.clear();
loginAddressController.clear();
});
}
//=====> FOR INSTANCES OF FIREBASE <=====
final auth = FirebaseAuth.instance;
final db = FirebaseFirestore.instance;
User user = FirebaseAuth.instance.currentUser;
body: Padding(
padding: EdgeInsets.only(left: 20, right: 20),
child: StreamBuilder(
stream: db.collection("collection name").snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot){
if (!snapshot.hasData) {
return Center(
child: spinkit,
);
}
return ListView.builder (
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index){
return Stack(
children: [
Column(
children: [
Stack(
children: [
// ===> RETRIEVING USER DETAILS AND SHOWING IT IN A ROW <===
Container(
padding : EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CircleAvatar(
backgroundColor: Palette.mainColor,
radius: 50,
child: ClipOval(
child: SizedBox(
height: 150,
width: 150,
child: image == null ? Center(
// child: Image.asset("asset/images/placeholder.png", fit: BoxFit.cover,),
child: Image.network(snapshot.data.documents[index].get("image")),
):
Image.file(image, fit: BoxFit.cover,),
),
),
),
SizedBox(width: 16,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 0),
child: Text(snapshot.data.documents[index].get("Name"),
style: TextStyle(
letterSpacing: 2,
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold,
),),
),
SizedBox(height: 5,),
Text(snapshot.data.documents[index].get("Address"),
style: TextStyle(
letterSpacing: 2,
color: Colors.black54,
fontSize: 16,
),),
SizedBox(height: 5,),
Text(snapshot.data.documents[index].get("Number"),
style: TextStyle(
letterSpacing: 2,
color: Colors.black54,
fontSize: 16,
),),
],
),
),
Padding(
padding: EdgeInsets.only(left: 0, bottom: 15),
child: IconButton(
icon:Icon(Icons.edit, color: Palette.mainColor, ),
onPressed: () { },
),
),
],
),
),
],
),
],
),
],
);
},
);
},
),
)
The collection name is members
Try like this, stream of your widget should be like this, as said above.
db.collection("Users").document(user.uid).snapshots();
for length in Listview.builder, change it too
snapshot.data.length;
And last, All the data which you fetch data like this should change into
from:
snapshot.data.documents[index].get("image")
To:
snapshot.data["image"]
Note I didn't test it. So, it might or might not work.
First of All use a DocumentSnapshot Shown below:
StreamBuilder<DocumentSnapshot>
Make a collection to get current user Profile data.
db.collection("Users").doc(user.uid).snapshots();
Remove ListView.builder
To get an Email Address use the below Line
Text('${streamSnapshot.data['Email Address']}'),
Here is the complete Article https://medium.com/#kamranktk807/fetch-user-data-from-firestore-and-show-them-in-profile-screen-using-flutter-609d2533e703
By the way I sol this problem with the help of a Professional Flutter Developer SHAKIR ZAHID [shakirzahid191#gmail.com].

Iterate over firebase database nodes flutter

I want to iterate through the customers available and get the posts of every customer and show it inside a listview.
However, if i specify the database reference as final postsRef = FirebaseDatabase.instance.reference().child('Customers available').child(Uid).child('Posts').orderByChild('timestamp');, I get only the user's posts.
Below is my code for building the listview and another is my database reference. Thanks final postsRef = FirebaseDatabase.instance.reference().child('Customers available')
This is my Firebase Database Screenshot
future: postsRef.once(),
builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
if (snapshot.hasData) {
lists.clear();
Map<dynamic, dynamic> values = snapshot.data.value;
values.forEach((key, values) {
lists.add(values);
});
return new ListView.builder(
shrinkWrap: true,
itemCount: lists.length,
itemBuilder: (BuildContext context, int index) {
return Container(
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: Colors.grey[200]))
),
padding: EdgeInsets.all(SizeConfig.blockSizeHorizontal * 4),
child: Row(
children: <Widget>[
Container(
height: 50,
width: 50,
child: Container(
height: 50,
width: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(150),
image: DecorationImage(image: FirebaseImage('gs://tipy-98639.appspot.com/profile_pic'))
),
),
decoration: BoxDecoration(
color: Colors.grey,
image: DecorationImage(image: AssetImage('images/dp.png')),
borderRadius: BorderRadius.circular(150)
),
),
SizedBox(width: SizeConfig.blockSizeHorizontal * 3,),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('NAME', style: TextStyle(
fontFamily: 'myriadpro',
fontWeight: FontWeight.bold,
fontSize: SizeConfig.blockSizeVertical * 1.7
),),
SizedBox(height: SizeConfig.blockSizeVertical * 1,),
Text(lists[index]["text"],
maxLines: 20,
overflow: TextOverflow.clip,
style: TextStyle(
fontFamily: 'myriadpro',
fontSize: SizeConfig.blockSizeVertical * 1.7
),),
],
),
),
],
),
);
});
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.green),),
Text('Loading your posts... 🕑',
style: TextStyle(
fontFamily: 'myriadpro'
),
)
],
));
}),`

Resources