简体   繁体   English

需要您的支持:当我按下收藏按钮时,我想在我的 Flutter 数据库中获取产品 ID

[英]Need your HELD : I want to get the product ID in my Flutter database when I press the favorite button

I need to get the product ID when I click on the favorite button.单击收藏按钮时,我需要获取产品 ID。 To do a test, I manually write the product id (the red first square, in left).为了进行测试,我手动编写了产品 ID(左侧的红色第一个方块)。 I need when I click on the favorite button that it automatically retrieves the ID for find it in the Database in Flutter.我需要当我单击收藏按钮时,它会自动检索 ID 以便在 Flutter 的数据库中找到它。

I added its own identifier in its data (the purple square, on the right), thinking that it would be easier to recover it.我在其数据中添加了自己的标识符(右侧的紫色方块),认为恢复它会更容易。

So I need to link the "productID" to the different products so that they are automatically recognized when I click on the favorite button.所以我需要将“productID”链接到不同的产品,以便在我点击收藏按钮时自动识别它们。

Thank you in advance for your help ☺提前感谢您的帮助☺

为了更好地理解我的要求

To test my code my "productID" is equal to: productID = '-Ms-PlyiwIZEm9V5kM8f'要测试我的代码,我的“productID”等于: productID = '-Ms-PlyiwIZEm9V5kM8f'

My code:我的代码:

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

    }
  }

}

Code result (picture):代码结果(图片):

在此处输入图像描述

to fetch an id for specific product try something like this:要获取特定产品的 id,请尝试以下操作:

getAppProductDetail(String appProductDetail) async {
  return FirebaseFirestore.instance
      .collection("appProducts")
      .where("productId", arrayContains: appProductDetail)
      .snapshots();
}

Otherwise to get all products you can do like this:否则,要获得所有产品,您可以这样做:

getAppProducts(String appProductDetail) {
  FirebaseFirestore.instance
      .collection("appProducts")
      .doc(appProductDetail)
      .get()
      .catchError((e) {
    print(e);
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter 带有收藏按钮的 Firestore 项目。 当我按下某个项目的收藏按钮时,它会使所有其他项目按钮也变为红色 - 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 在 Flutter Web 应用程序中按 Altright 时出错 - Error when I press Altright in my Flutter web application 我希望能够在我的 firebase 数据库中获取自动生成的 id 子值,并在 function 中使用它们 - I want to be able to get the auto generated id child values in my firebase database and use them within a function 我想从Firebase提取产品ID - I want to fetch Product ID from Firebase 我需要使用Android Studio在Firebase数据库中的FirebaseAuthentication用户ID下获取数据 - I need to get data under FirebaseAuthentication user Id in my Firebase database using android studio 我想从我的 Firestore 中获取文档 ID - I want to get document id from my firestore 当我希望使用currentUser()的Firebase用户ID时为Null错误 - Null error when I want my firebase user id with currentUser() 我在 flutter 中构建项目时出现以下错误 - I get the following error when i build my project in flutter 在 Firebase 中使用 push() 如何获取唯一 ID 并存储在我的数据库中 - In Firebase when using push() How do I get the unique ID and store in my database 我想在Ionic 3的购物车中获得所有产品价格的总和 - I want to get the sum total of all product prices in my cart in Ionic 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM