简体   繁体   中英

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. To do a test, I manually write the product id (the red first square, in left). I need when I click on the favorite button that it automatically retrieves the ID for find it in the Database in 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.

Thank you in advance for your help ☺

为了更好地理解我的要求

To test my code my "productID" is equal to: 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM