Home > Enterprise >  Product list is not Showing in this flutter screen
Product list is not Showing in this flutter screen

Time:11-01

My product has been added to Firebase, but there is a problem with the dashboard's list not appearing. No errors are displayed on the console or the screen.I'm not sure where the problem is appearing in the code or firebase. I'm basically developing an e-commerce app that users should use to sell their goods.

class _SellerDashBoardState extends State<SellerDashBoard> {
  MaterialColor active = Colors.red;

  MaterialColor notActive = Colors.grey;

  List<SellerProductItem> products = [
    const SellerProductItem(),
  ];

  @override
  Widget build(BuildContext context) {
    print(parentIdGlobal);
    print(FirebaseAuth.instance.currentUser!.uid);
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
        title: Text(
          'Seller Dashboard',
          style: TextStyle(
              fontSize: ResponsiveWidget.isSmallScreen(context) ? 17.0 : 25.0),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.add_circle),
            iconSize: 27.0,
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (BuildContext context) => AddProductForm(),
                ),
              );
            },
          ),
          IconButton(
            icon: WebsafeSvg.asset(
              'assets/images/sold-out.svg',
            ),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (BuildContext context) => SoldItemScreens(),
                ),
              );
            },
          ),
        ],
      ),
      body: Column(
        children: <Widget>[
          const SizedBox(
            height: 10.0,
          ),
          Container(
              color: const Color(0xffF7F7F7),
              child: StreamBuilder(
                stream: FirebaseFirestore.instance
                    .collection("items")
                    .where('seller', isEqualTo: parentIdGlobal)
                    .where('isSold', isEqualTo: true)
                    .snapshots(),
                builder: (context, AsyncSnapshot snapshot) {
                  if (!snapshot.hasData) {
                    return const Center(child: CircularProgressIndicator());
                  }
                  final List<QueryDocumentSnapshot<Map<String, dynamic>>>
                      docSnapList = snapshot.data?.docs ?? [];

                  if (docSnapList.isEmpty) {
                    return Center(
                      child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: WebsafeSvg.asset(
                          'assets/images/empty_dashboard.svg',
                          fit: BoxFit.cover,
                          height: MediaQuery.of(context).size.height / 5,
                        ),
                      ),
                    );
                  }
                  final List<Map<String, dynamic>> docList = docSnapList
                      .map((QueryDocumentSnapshot<Map<String, dynamic>>
                              queryDocumentSnapshot) =>
                          queryDocumentSnapshot.data())
                      .toList();
                  return ListView.builder(
                    scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                    itemCount: docList.length,
                    itemBuilder: (context, index) {
                      bool isSold = docList[index]['isSold'] ?? true;
                      bool isLiked = docList[index]['isLiked'] ?? true;
                      String itemId = docList[index]['itemId'] ?? '';
                      String seller = docList[index]['seller'] ?? '';
                      String sellerName = docList[index]['sellerName'] ?? '';
                      String title = docList[index]['title'] ?? '';
                      String desc = docList[index]['desc'] ?? '';
                      String price = docList[index]['price'] ?? '';
                      String condition = docList[index]['condition'] ?? '';
                      String category = docList[index]['category'] ?? '';
                      String location = docList[index]['location'] ?? '';
                      String itemImage =
                          docList[index]['imageDownloadUrl'] ?? '';

                      return SellerProductItem(
                        itemId: itemId,
                        seller: seller,
                        sellerName: sellerName,
                        title: title,
                        desc: desc,
                        price: price,
                        itemImage: itemImage,
                        isLiked: isLiked,
                        isSold: isSold,
                        category: category,
                        condition: condition,
                        location: location,
                      );
                    },
                  );
                },
     

add product screen

class _AddProductFormState extends State<AddProductForm> {
  TextEditingController controllerTitle = TextEditingController();
  TextEditingController controllerPrice = TextEditingController();
  TextEditingController controllerDescription = TextEditingController();
  TextEditingController controllerlocation = TextEditingController();

  GlobalKey<FormState> _formKey = GlobalKey();
  String selectedCondition = 'New';
  String selectedCategory = 'Cosmetic Aids';
  bool isReadOnly = true;
  File? pickedImage;
  bool imgStatus = false;

  List<String> conditionList = [
    'New',
    'Like New',
    'Good',
    'Fair',
    'Poor',
  ];

  List<String> categoryList = [
    'Cosmetic Aids',
    'Mobility Products',
    'Bath Safety Products',
    'Others',
  ];

  bool _switchValue = false;

  Future<void> addGroceryItemToToDb() async {
    final itemId = Uuid().v4();
    String? url;

    if (pickedImage != null) {
          print(parentIdGlobal);
    print(FirebaseAuth.instance.currentUser!.uid);

      Reference storage = FirebaseStorage.instance
          .ref()
          .child('users/${FirebaseAuth.instance.currentUser!.uid}/$itemId/item_pic');
      UploadTask uploadTask = storage.putFile(pickedImage!);

      final temp = await (await uploadTask).ref.getDownloadURL();
      url = temp.toString();
    }

    FirebaseFirestore.instance.collection('items').doc(itemId).set(
      {
        'itemId': itemId,
        'timestamp': DateTime.now(),
        'seller': parentIdGlobal,
        'sellerName': userNameGlobal,
        'title': controllerTitle.text,
        'price': controllerPrice.text,
        'desc': controllerDescription.text,
        'condition': selectedCondition,
        'category': selectedCategory,
        'location': controllerlocation.text,
        'isSold': false,
        'imageDownloadUrl': url,
      },
    );
  } // adds grocery item to db

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 1.0,
        centerTitle: true,
        title: Text(
          'Add a Product',
        ),
      ),
      body: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              _selectImageButton(context),
              _writeTitle(),
              _writePrice(),
              _giveitfree(),
              _conditionDropDown(),
              _writeDescription(),
              _categoryDropDown(),
              _writeLocation(),
              Align(
                  alignment: Alignment.bottomCenter,
                  child: _addProductButton(context)),
            ],
          ),
        ),
      ),
    );
  }

  _selectImageButton(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        await Permission.photos.request();
        var status = await Permission.photos.status;
        if (status.isGranted) {
          try {
            XFile? _pickedImage = await ImagePicker().pickImage(
              source: ImageSource.gallery,
              maxWidth: 100,
              maxHeight: 100,
              imageQuality: 100
            ) ;
            if(_pickedImage !=null){
              pickedImage = File(_pickedImage.path);
              setState(() {
              imgStatus = true;
            });
          } }catch (e) {
            print(e.toString());
          }
        } else if (status.isDenied || status.isRestricted) {
          print('Permission Denied');

          showDialog(
              context: context,
              builder: (context) {
                if (Platform.isAndroid)
                  return AlertDialog(
                    title: Text('Permission Not Granted'),
                    content:
                        Text('The permission for photo library is not granted'),
                    actions: [
                      ElevatedButton(
                        onPressed: () => openAppSettings(),
                        child: Text('Ok'),
                      ),
                    ],
                  );
                return CupertinoAlertDialog(
                  title: Text('Permission Not Granted'),
                  content:
                      Text('The permission for photo library is not granted'),
                  actions: [
                    ElevatedButton(
                      onPressed: () => openAppSettings(),
                      child: Text('Ok'),
                    ),
                  ],
                );
              });
        } else if (status.isDenied) {
          print('Permission Undetermined');
        }
      },
      child: Padding(
        padding: EdgeInsets.only(
          top: 10.0,
          bottom: 10.0,
        ),
        child: Container(
          height: 100.0,
          width: 100.0,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0),
            color: Colors.transparent,
            border: Border.all(
              style: BorderStyle.solid,
              color: Colors.red,
            ),
          ),
          child: pickedImage == null
              ? Icon(
                  Icons.add,
                  color: Colors.red,
                )
              : Image.file(
                  pickedImage!,
                  fit: BoxFit.contain,
                ),
        ),
      ),
    );
  }

  ButtonTheme _addProductButton(BuildContext context) {
    return ButtonTheme(
      minWidth: MediaQuery.of(context).size.width / 1.1,
      child: ElevatedButton(
        onPressed: imgStatus
            ? () async {
                if (_formKey.currentState?.validate() == true) {
                  try {
                    Navigator.pop(context);
                    await addGroceryItemToToDb();
                  } catch (error) {
                    print(error);
                  }
                }
              }
            : null,
        child: Text(
          'Add Product',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  Padding _writeDescription() {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 8.0,
        horizontal: 10.0,
      ),
      child: TextFormField(
        controller: controllerDescription,
        maxLines: 5,
        inputFormatters: [
          new LengthLimitingTextInputFormatter(
            1450,
          ),
        ],
        maxLength: 1450,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          isDense: true,
          labelText: 'Description',
          helperText: "Describe what you're selling in detail",
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
        ),
      ),
    );
  }

  Padding _conditionDropDown() {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 8.0,
        horizontal: 10.0,
      ),
      child: conditionDropdownbuttonStyle(),
    );
  }

  Widget conditionDropdownbuttonStyle() {
    List<Text> pickerItems = [];
    for (String condition in conditionList) {
      pickerItems.add(Text(condition));
    }
    if (Platform.isIOS) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            'Condition',
            textAlign: TextAlign.left,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(
            height: 10,
          ),
          CupertinoPicker(
            backgroundColor: Colors.white70,
            useMagnifier: true,
            itemExtent: 32.0,
            diameterRatio: 2,
            scrollController: FixedExtentScrollController(initialItem: 0),
            magnification: 1.2,
            onSelectedItemChanged: (selectedIndex) {
              print(selectedIndex);
              selectedCondition = conditionList[selectedIndex];
              print(selectedCondition);
            },
            children: pickerItems,
          ),
        ],
      );
    }

    List<DropdownMenuItem<String>> dropDownItem = [];
    for (String condition in conditionList) {
      print(condition);
      var newItem = DropdownMenuItem<String>(
        child: Text(condition),
        value: condition,
      );
      dropDownItem.add(newItem);
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Text(
          'Condition',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(
          width: 10.0,
        ),
        Expanded(
          child: DropdownButton<String>(
            items: dropDownItem,
            isExpanded: true,
            value: selectedCondition,
            hint: Text(
              'Condition',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            onChanged: (value) {
              setState(() {
                 if (value != null) {
                   selectedCondition = value;
                 }
              });
            },
          ),
        )
      ],
    );
  }

  Padding _categoryDropDown() {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 8.0,
        horizontal: 10.0,
      ),
      child: categoryDropdownbuttonStyle(),
    );
  }

  Widget categoryDropdownbuttonStyle() {
    List<Text> pickerItems1 = [];
    for (String category in categoryList) {
      pickerItems1.add(Text(category));
    }
    if (Platform.isIOS) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            'Category',
            textAlign: TextAlign.left,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(
            height: 10,
          ),
          CupertinoPicker(
            backgroundColor: Colors.white70,
            useMagnifier: true,
            itemExtent: 32.0,
            diameterRatio: 2,
            scrollController: FixedExtentScrollController(initialItem: 0),
            magnification: 1,
            onSelectedItemChanged: (selectedIndex) {
              print(selectedIndex);
              selectedCategory = categoryList[selectedIndex];
              print(selectedCategory);
            },
            children: pickerItems1,
          ),
        ],
      );
    }

    List<DropdownMenuItem<String>> dropDownItem = [];
    for (String category in categoryList) {
      print(category);
      var newItem = DropdownMenuItem<String>(
        child: Text(category),
        value: category,
      );
      dropDownItem.add(newItem);
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Text(
          'Category',
          textAlign: TextAlign.left,
          style: TextStyle(
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(
          width: 10.0,
        ),
        Expanded(
          child: DropdownButton<String>(
            items: dropDownItem,
            isExpanded: true,
            value: selectedCategory,
            hint: Text(
              'Category',
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            onChanged: (value) {
              setState(() {
                  if (value != null) {
                    selectedCategory = value;}
              });
            },
          ),
        )
      ],
    );
  }

  Padding _giveitfree() {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 8.0,
        horizontal: 10.0,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            'Give it away for free',
            maxLines: 1,
            style: TextStyle(
              fontWeight: FontWeight.w600,
            ),
          ),
          switchButtonType(),
        ],
      ),
    );
  }

  Widget _writePrice() {
    if (_switchValue) {
      return Container(
        width: 0.0,
        height: 0.0,
      );
    }
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 8.0,
        horizontal: 10.0,
      ),
      child: TextFormField(
        controller: controllerPrice,
        maxLines: 1,
        inputFormatters: [
          new LengthLimitingTextInputFormatter(
            5,
          ),
          FilteringTextInputFormatter.digitsOnly,
        ],
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.attach_money),
          isDense: true,
          labelText: 'Price',
          helperText: 'Set your Price',
          hintText: 'Default Price: 0 \u0024',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
        ),
      ),
    );
  }

  Padding _writeTitle() {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 8.0,
        horizontal: 10.0,
      ),
      child: TextFormField(
        validator: (value) {
          if (value != null) {
            if (value.length < 5) {
            return 'The title should be at least 5 characters';
          }
          return null;
        };
return null;},
        controller: controllerTitle,
        maxLines: 1,
        inputFormatters: [
          new LengthLimitingTextInputFormatter(
            50,
          ),
        ],
        decoration: InputDecoration(
          prefixIcon: Icon(
            Icons.title,
          ),
          isDense: true,
          labelText: 'Title*',
          labelStyle: TextStyle(
            color: Colors.red,
          ),
          helperText: 'Describe your Product in few words',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(
              8.0,
            ),
          ),
        ),
      ),
    );
  }

  Padding _writeLocation() {
    return Padding(
      padding: EdgeInsets.symmetric(
        vertical: 8.0,
        horizontal: 10.0,
      ),
      child: TextFormField(
        controller: controllerlocation,
        maxLines: 1,
        inputFormatters: [
          new LengthLimitingTextInputFormatter(
            50,
          ),
        ],
        decoration: InputDecoration(
          prefixIcon: Icon(
            Icons.location_on,
          ),
          suffixIcon: IconButton(
            icon: Icon(Icons.near_me),
            onPressed: getLocation,
          ),
          isDense: true,
          labelText: 'Location',
          helperText: 'Eg: Austin,Texas',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
        ),
      ),
    );
  }

  getLocation() async {
    try {
      await Permission.location.request();
      var status = await Permission.location.status;
      if (status.isGranted) {
        print('Permission Granted');
        Position position = await Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.best);
        print(position);
        double latitude = position.latitude;
        double longitude = position.longitude;
        print('latitude: $latitude \n longitude: $longitude');
        List<Placemark> placemark = await placemarkFromCoordinates(
          latitude,
          longitude,
        );
        setState(() {
          print(placemark[0]);
          controllerlocation.text =
              ('${placemark[0].locality},${placemark[0].administrativeArea},${placemark[0].country}')
                  .toString();
        });
      } else if (status.isDenied || status.isRestricted) {
        print('Permission Denied');

       

  Widget switchButtonType() {
    if (Platform.isAndroid) {
      return Switch(
        value: _switchValue,
        onChanged: (value) {
          setState(
            () {
              _switchValue = value;
              isReadOnly = _switchValue;
              controllerPrice.text = '0';
              print(_switchValue);
            },
          );
        },
      );
    }
    return CupertinoSwitch(
      value: _switchValue,
      onChanged: (value) {
        setState(
          () {
            _switchValue = value;
            isReadOnly = _switchValue;
            controllerPrice.text = '0';
            print(_switchValue);
          },
    

CodePudding user response:

You are filtering items that have isSold set to true but when adding you are adding with isSold set to false. Maybe you should change your filter to .where('isSold', isEqualTo: false)?

  • Related