[英]Flutter firestore items with favorite button. when i press the favorite button for an item it makes all the other items button to red also
[英]Need your HELD : I want to get the product ID in my Flutter database when I press the favorite button
单击收藏按钮时,我需要获取产品 ID。 为了进行测试,我手动编写了产品 ID(左侧的红色第一个方块)。 我需要当我单击收藏按钮时,它会自动检索 ID 以便在 Flutter 的数据库中找到它。
我在其数据中添加了自己的标识符(右侧的紫色方块),认为恢复它会更容易。
所以我需要将“productID”链接到不同的产品,以便在我点击收藏按钮时自动识别它们。
提前感谢您的帮助☺
要测试我的代码,我的“productID”等于: productID = '-Ms-PlyiwIZEm9V5kM8f'
我的代码:
import 'dart:async';
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:like_button/like_button.dart';
import 'package:potbelly/add_products/itemdetails2.dart';
import 'package:potbelly/add_products/tools/app_data.dart';
import 'package:potbelly/add_products/tools/app_methods.dart';
import 'package:potbelly/add_products/tools/firebase_methods.dart';
import 'package:potbelly/routes/router.dart';
import 'package:potbelly/routes/router.gr.dart';
import 'package:potbelly/screens/home_screen.dart';
import 'package:potbelly/values/values.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
static const int TAB_NO = 0;
}
class _MyHomePageState extends State<MyHomePage> {
BuildContext context;
String acctPhotoURL = "";
bool isLoggedIn;
AppMethods appMethods = new FirebaseMethods();
Firestore firestore = Firestore.instance;
bool _isLiked = false;
bool isLiked = false;
int likeCount = 0;
@override
Widget build(BuildContext context) {
this.context = context;
return new Scaffold(
appBar: AppBar(
elevation: 0.0,
leading: InkWell(
onTap: () => AppRouter.navigator.pushNamedAndRemoveUntil(
AppRouter.rootScreen,
(Route<dynamic> route) => false,
arguments: CurrentScreen(
tab_no: HomeScreen.TAB_NO,
currentScreen: HomeScreen(),
),
),
child: Image.asset(
ImagePath.arrowBackIcon,
color: AppColors.headingText,
),
),
centerTitle: true,
title: Text(
'Articles',
style: Styles.customTitleTextStyle(
color: AppColors.headingText,
fontWeight: FontWeight.w600,
fontSize: Sizes.TEXT_SIZE_20,
),
),
),
body: new StreamBuilder(
stream: firestore.collection(appProducts).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return new Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).primaryColor)));
} else {
final int dataCount = snapshot.data.documents.length;
if (dataCount == 0) {
return noDataFound();
} else {
return new GridView.builder(
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, childAspectRatio: 0.85),
itemCount: dataCount,
itemBuilder: (context, index) {
final DocumentSnapshot document =
snapshot.data.documents[index];
return buildProducts(context, index, document);
},
);
}
}
}),
);
}
Widget noDataFound() {
return new Container(
child: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Icon(
Icons.find_in_page,
color: Colors.black45,
size: 80.0,
),
new Text(
"Not Product avaliable yet. ",
style: new TextStyle(color: Colors.black45, fontSize: 20.0),
),
new SizedBox(
height: 10.0,
),
new Text(
"Please check back later",
style: new TextStyle(color: Colors.red, fontSize: 14.0),
),
])));
}
Widget buildProducts(
BuildContext context, int index, DocumentSnapshot document) {
List productImage = document[productImages] as List;
return InkWell(
onTap: () {
Navigator.of(context).push(new MaterialPageRoute(
builder: (context) => new ItemDetail2(
itemImage: productImage[0],
itemImages: productImage,
itemName: document[productTitle],
itemSubName: document[productCat],
itemDescription: document[productDesc],
itemColor: document[productColor],
itemSize: document[productSize],
itemLoc: document[productLoc],
itemCat: document[productCat],
itemFav: document[favorites],
itemId: document[productid],
)
));
},
child: Container(
margin: EdgeInsets.all(2.0),
width: 340.0,
height: 280.0,
child: Card(
elevation: 4.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: Stack(
alignment: FractionalOffset.topLeft,
children: <Widget>[
new Stack(
alignment: FractionalOffset.bottomCenter,
children: <Widget>[
Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(12.0),
image: new DecorationImage(
fit: BoxFit.cover,
image: new NetworkImage(productImage[0]))),
),
new Container(
height: 50.0,
width: 200.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(12), bottomRight: Radius.circular(12),),
color: Colors.black.withAlpha(100),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
"${document[productTitle]}",
style: new TextStyle(
fontWeight: FontWeight.w700,
fontSize: 16.0,
color: Colors.white),
),
],
),
)
],
),
Positioned(
top: 4,
right: 4.0,
child: new LikeButton(
onTap: onLikeButtonTapped,
size: 30,
isLiked: isLiked,
likeBuilder: (isLiked){
final bookmarks = isLiked ? ImagePath.activeBookmarksIcon : ImagePath.bookmarksIcon_fav;
return Image.asset(bookmarks);
},
),
)
],
),
),
),
);
}
Future<bool> onLikeButtonTapped(bool isLiked) async{
updateFavorite(isLiked, '-Ms-PlyiwIZEm9V5kM8f', context);
return !isLiked;
}
updateFavorite(isLiked, String productID, context) async{
final FirebaseAuth auth = FirebaseAuth.instance;
final FirebaseUser user = await auth.currentUser();
if (isLiked == false) {
Firestore.instance.collection("appProducts").document(productID).updateData({
'favorites': FieldValue.arrayUnion([user.uid]),
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Added to my fav'),)
);
} else {
Firestore.instance.collection("appProducts").document(productID).updateData({
'favorites': FieldValue.arrayRemove([user.uid]),
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Removed from fav'),)
);
}
}
}
代码结果(图片):
要获取特定产品的 id,请尝试以下操作:
getAppProductDetail(String appProductDetail) async {
return FirebaseFirestore.instance
.collection("appProducts")
.where("productId", arrayContains: appProductDetail)
.snapshots();
}
否则,要获得所有产品,您可以这样做:
getAppProducts(String appProductDetail) {
FirebaseFirestore.instance
.collection("appProducts")
.doc(appProductDetail)
.get()
.catchError((e) {
print(e);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.