How to make changes at the particular index of a list whose data is fetched from cloud Firestore in flutter? - firebase

In my flutter application, i fetched my data in a list from Firestore and now want to an ADD or REMOVE option for increasing or decreasing the number of units of that particular item on the list but after several tries not able to do that as the count on the entire list gets updated not that particular element in that index. Can anyone help me in this
CustomScrollView(
physics: BouncingScrollPhysics(),
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate((context, index){
return Container(
margin: EdgeInsets.only(top: 15.0,left: 15.0,right: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: Text(snapshot.data.documents[index].documentID,style: TextStyle(fontFamily: "DelishN", fontSize: 15.0),),
),
Container(
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: Colors.black
),
borderRadius: BorderRadius.circular(23.0)
),
child: Row(
children: <Widget>[
FloatingActionButton(
onPressed: (){
add();
},
mini: true,
child: Icon(Icons.add, color: Colors.black,),
backgroundColor: Colors.white,
),
SizedBox(
width: 7.0,
),
Text(_n.toString(), style: TextStyle(fontFamily: 'DelishN',),),
SizedBox(
width: 7.0,
),
FloatingActionButton(
onPressed: (){
minus();
},
mini: true,
child: Icon(Icons.remove, color: Colors.black,),
backgroundColor: Colors.white,)
],
),
)
],
)
);
},
childCount: snapshot.data.documents.length))],
)

Related

fetch data from firebase firestore instead of constants

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

How to know which card is tapped in flutter

I am making my first flutter app (A coffee shop), in this I have accessed data from Firebase Cloudstore and displayed it in the form of card.
Now I have provided the user with the feature of customizing order
for that I have to know which item he is customizing and hence I need to know which card the user has tapped.
Here is my code snippet:
child: GestureDetector(
onTap: (){
return showModalBottomSheet<void>(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(40.0),
topLeft: Radius.circular(40.0),
)
),
context: context,
builder: (BuildContext context) {
return Container(
child: CustomOrder(),
height: 400.0,
width: 350.0,
);
},
);
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0),
),
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: Image(
image: AssetImage('assets/coff1.PNG'),
),
),
Align(
alignment: Alignment.topLeft,
child: Text(
'${itemslist[index]["item_name"]}',
style: TextStyle(
fontSize: 38.0,
fontFamily: 'GrandHotel',
fontWeight: FontWeight.bold,
color: Colors.brown[800]
),
// textAlign: TextAlign.left
),
),
Align(
alignment: Alignment.topLeft,
child: Text(
'${itemslist[index]["price"]}',
style: TextStyle(
fontSize: 22.0,
fontFamily: 'GrandHotel',
color: Colors.brown[800]
),
),
),
Align(
alignment: Alignment.topLeft,
child: Text(
'${itemslist[index]["desc"]}',
style: TextStyle(
fontSize: 22.0,
fontFamily: 'GrandHotel',
color: Colors.brown[800]
),
),
),
SizedBox(height: 10.0),
FlatButton.icon(
color: Colors.brown[400],
onPressed: (){},
icon: Icon(Icons.add),
label: Text(
"Add to cart",
style: TextStyle(
fontSize: 20.0,
color: Colors.brown[800]
),
),
),
]
),
),
),
),
It appears that you are using a listView.builder but didn't attach it to your code properly, but you are accessing this [index] in your code.
Therefore, in your onpressed button in the bottom,
onPressed: (){
print(itemslist[index]["item_name"]);} // should print your tapped item's name, and then you can do whatever you want if you have reached this far.
I would wrap each separate card with their own GestureDetector. If you need more instruction for implementing this, just let me know in the comments.

Show Spinner using ModalProgressHUD in Flutter whilst ListView.builder reads information from Firebase

I have a screen where I try to read all my documents as a list using a Listview.builder in Flutter. I want to use ModalProgressHUD to show circular spinner whilst data is read from Firebase. When it's done building, I want to stop showing circular spinner by setting showSpinner to false.
I can hack this for a form screen but can't seem to for this view all screen, perhaps it's because it's a Listview.builder.
Thanks in advance.
Code below:
//class wide declaration
bool showSpinner = true;
Widget build(BuildContext context) {
ExpenseNotifier expenseNotifier = Provider.of<ExpenseNotifier>(context);
Future<void> _resfreshList() async {
expenseNotifier.getExpenses(expenseNotifier);
}
return Scaffold(
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: RefreshIndicator(
onRefresh: _resfreshList,
child: Consumer<ExpenseNotifier>(
builder: (context, expense, child) {
return expense == null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
PaddingClass(bodyImage: 'images/empty.png'),
SizedBox(
height: 20.0,
),
Text(
'You don\'t have any expenses',
style: kLabelTextStyle,
),
],
)
: ListView.separated(
itemBuilder: (context, int index) {
var myExpense = expense.expenseList[index];
return Card(
elevation: 8.0,
color: Colors.white70,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
RegularExpenseTextPadding(
regText:
'${_formattedDate(myExpense.updatedAt)}',
),
Container(
margin: EdgeInsets.all(20.0),
padding: const EdgeInsets.all(15.0),
decoration: BoxDecoration(
borderRadius:
BorderRadius.all(Radius.circular(5.0)),
border: Border.all(
color: kThemeStyleBorderHighlightColour),
),
child: Row(
children: <Widget>[
Expanded(
flex: 5,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
'${myExpense.amount}',
style: kRegularTextStyle,
),
SizedBox(
height: 20.0,
),
Text(
myExpense.description,
style: kRegularTextStyle,
),
],
),
),
Expanded(
flex: 1,
child: GestureDetector(
onTap: () {
expenseNotifier.currentExpense =
expenseNotifier
.expenseList[index];
Navigator.of(context).push(
MaterialPageRoute(builder:
(BuildContext context) {
return ExpenseDetailsScreen();
}));
},
child: Icon(
FontAwesomeIcons.caretDown,
color: kThemeIconColour,
),
),
),
],
),
),
],
),
);
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 20.0,
);
},
itemCount: expenseNotifier.expenseList.length,
);
},
),
),
),
);
}

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'
),
)
],
));
}),`

How do I generate a list of widgets from firebase firestore database?

I'm trying to figure out how to iterate through documents in firestore and create a text widget for each one.
I've figured out how to access those elements. I used debugPrint() and got the results I'm expecting, but I can't get it to display below my other widgets. I get a red screen with a ton of errors (on phone).Below is my code for what I've tried so far.
QuerySnapshot querySnapshot = await
Firestore.instance.collection("users").document(user.uid).collection("trails").getDocuments();
var list = querySnapshot.documents;
list.forEach((doc) => debugPrint(doc.data["Trail Name"].toString()));//works
final topContentText = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
//these widgets are generating correctly
Text(
"First Name: $firstName",
style: TextStyle(color: Colors.white, ),
),
Text(
"Last Name: $lastName",
textAlign: TextAlign.left,
style: TextStyle(color: Colors.white,),
),
Text(
"Email: $email",
style: TextStyle(color: Colors.white, ),
),
//these ones are causing my errors.
list.forEach((doc) => Text(
"Trail Name: ${doc.data["Trail Name"].toString()}",
style: TextStyle(color: Colors.white, ),
),)
],
);
final topContent = Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.40,
padding: EdgeInsets.all(40.0),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(color: Color.fromRGBO(58, 66, 86, .9)),
child: Center(
child: topContentText,
),
),
Positioned(
left: 8.0,
top: 60.0,
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back, color: Colors.white),
),
)
],
);
return Scaffold(
body: Column(
children: <Widget>[topContent, bottomContent],
),
);
The screen on my device lights up red with errors on creating child widgets, when I'm expecting it to display the Trail Name(s) below the other info. I only included necessary code, but could include more (such as the widget's build method) if needed. Thanks for any assistance. I'm new to flutter.
Try using the map function:
List<Widget> _widgets = list.map((doc) => Text(
"Trail Name: ${doc.data["Trail Name"].toString()}",
style: TextStyle(color: Colors.white, ),
),).toList();
And then for the children of the column, just add that list to the list you specify, like:
children: [ ... ] + _widgets;

Resources