首页 > 解决方案 > 使用标签栏过滤 GridView 中的项目

问题描述

我有一个包含 Gridview 的 Listview,我正在尝试根据列表视图中的列表标题过滤结果,但似乎无法使其工作。

当我点击选项卡按钮时,我希望网格视图仅显示具有匹配属性的产品。这是我的应用程序的外观供参考:

编辑 1:_changedDropDownItem

 void _changedDropDownItem(int newValue) {
    setState(() {
      _selectedCustomerType = newValue;
    });

    makeDropdown(newValue);

    print(_selectedCustomerType);
  }

  void makeDropdown(filterNumb) {
    if (filterNumb == 0) {
      _dropdownList = _all;
    } else if (filterNumb == 1) {
      _dropdownList = _feeling;
    } else if (filterNumb == 2) {
      _dropdownList = _productType;
    } else if (filterNumb == 3) {
      _dropdownList = _filter;
    }
    // _sortTabs(filterNumb, _filterCat, _productTabFilter, _dropdownList);
    print(_dropdownList);
  }

在此处输入图像描述

每个选项卡的标题如下:

List _all = ['All'];

  List _feeling = [
    'Creativity',
    'Energetic',
    'Euphoric',
    'Focused',
    'Giggly',
    'Happy',
    'Hungry',
    'Relaxed',
    'Sleepy',
    'Sexy Time',
    'Talkative',
    'Tingly',
    'Uplifted',
  ];

  List _productType = [
    'Flower',
    'Concentrates',
    'Dabs',
    'For Pets',
    'Storage',
    'Topical',
    'Vaping',
    'Home Setup',
    'Edibles',
    'Pre-Rolled',
    'Bongs & Pipes',
  ];

  List _usage = [
    'Headache',
    'Insomnia',
    'Being Social',
    'First Timers',
    'Cramps\n & Pains',
    'Body Pains',
    'Stress and\n Tension',
    'Creativity',
    'Productivity',
    'Accessory',
  ];

  List _filter = [
    'Headache',
    'Insomnia',
    'Being Social',
    'First Timers',
    'Cramps\n & Pains',
    'Body Pains',
    'Stress and\n Tension',
    'Creativity',
    'Productivity',
    'Accessory',
  ];

创建列表视图

 Container(
              child: ListView.builder(
            scrollDirection: Axis.vertical,
            itemCount: _dropdownList.length,
            shrinkWrap: true,
            itemBuilder: (context, _tabIndex) {
              return Container(child: _buildProduct(context, _tabIndex));
            },

编辑 2:JSON 数据:

{
    "product": [
        {
            "id": 28,
            "name": "Blueberry Waltz",
            "short_description": "Blue Frost is a hybrid that balances the genetics of Blue Monster and Jack Frost to create a 60/40 indica-dominant cross. Breeder Goldenseed has developed this strain to produce dense buds that show a range of deep violet hues and produces a pungent mixture of aromas. The flavor is an interesting combination of sweet fruity notes with a sharp cheese-like undertone. This hybrid is sure to lift your mood and replace any stress you may have with smile on your face.",
            "usage": "First Timers",
            "effect": "Energetic",
            "quantity": 20,
            "sizes": [
                {
                    "id": 57,
                    "size": 3,
                    "product_id": 28,
                    "price": 25.0
                },
                {
                    "id": 58,
                    "size": 4,
                    "product_id": 28,
                    "price": 50.0
                }
            ],
            "image": "https://dispensaries.s3.amazonaws.com/product_images/grams.png",
            "image2": "https://dispensaries.s3.amazonaws.com/product_images/blueberry-waltz-1.jpg",
            "image3": "https://dispensaries.s3.amazonaws.com/product_images/GRAND-DADDY-PURPLE.jpg",
            "Product_Type": "Carry Case",
            "Product_Category": "Pets",
            "thc_content": 92.0,
            "cbd_content": 0.0
        },
        {
            "id": 27,
            "name": "Pink Champagne",
            "short_description": "Wrawer",
            "usage": "First Timers",
            "effect": "Creative",
            "quantity": 9,
            "sizes": [
                {
                    "id": 56,
                    "size": 2,
                    "product_id": 27,
                    "price": 29.99
                }
            ],
            "image": "https://dispensaries.s3.amazonaws.com/product_images/char.png",
            "image2": "https://dispensaries.s3.amazonaws.com/product_images/Pink_Champagne_A3pza9w.jpeg",
            "image3": "https://dispensaries.s3.amazonaws.com/product_images/Pink_Champagne_V65X8hn.jpeg",
            "Product_Type": "Cartridge",
            "Product_Category": "Storage",
            "thc_content": 23.2,
            "cbd_content": 20.0
        }
{
            "id": 29,
            "name": "test prod",
            "short_description": "wassup",
            "usage": "First Timers",
            "effect": "Euphoric",
            "quantity": 4,
            "sizes": [
                {
                    "id": 59,
                    "size": 3,
                    "product_id": 29,
                    "price": 29.99
                }
            ],
            "image": "https://dispensaries.s3.amazonaws.com/product_images/1_1.png",
            "image2": "https://dispensaries.s3.amazonaws.com/product_images/2_1.png",
            "image3": "https://dispensaries.s3.amazonaws.com/product_images/2.png",
            "Product_Type": "indica",
            "Product_Category": "Dabs",
            "thc_content": 20.0,
            "cbd_content": 0.0
        }
    ]
}

使用数据创建产品 GridView

Widget _buildProduct(BuildContext context, _tabIndex) {
    return Container(
        child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(left: 8.0, top: 8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      _dropdownList[_tabIndex],
                      style: TextStyle(
                          fontFamily: 'Poppins',
                          color: buddiesPurple,
                          fontSize: 18),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: screenAwareSize(10, context),
              ),
              Container(
                  // padding: EdgeInsets.only(top: 10.0),
                  // height: 350,
                  width: MediaQuery.of(context).size.width,
                  child: FutureBuilder(
                    future: _setProducts,
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      switch (snapshot.connectionState) {
                        case ConnectionState.waiting:
                          return Center(
                            child: CircularProgressIndicator(),
                          );
                          break;
                        case ConnectionState.none:
                          break;
                        case ConnectionState.active:
                          break;

                        case ConnectionState.done:
                          if (snapshot.hasError)
                            return Text('Error: ${snapshot.error}');
                          else
                            productList = snapshot.data;
                          _productTabFilter = snapshot.data;

                          break;
                      }

                      return GridView.builder(
                        itemCount: _productTabFilter.length,
                        controller: ScrollController(),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            mainAxisSpacing: 20,
                            childAspectRatio: 0.7),
                        shrinkWrap: true,
                        scrollDirection: Axis.vertical,
                        itemBuilder: (context, i) {

                          return InkWell(
                            onTap: () {
                              currentRes = restaurant;
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => SelectedProduct(
                                            restaurant: restaurant,
                                            product: _productTabFilter[i],
                                          )));
                            },
                            child: Stack(children: <Widget>[
                              _buildProductList(
                                  _productTabFilter[i].name,
                                  _productTabFilter[i].image2,
                                  _productTabFilter[i].usage,
                                  _productTabFilter[i].effect,
                                  _productTabFilter[i].productType,
                                  '${_productTabFilter[i].sizes[0].price.toStringAsFixed(2)}',
                                  _productTabFilter[i].quantity)
                            ]),
                          );
                        },
                      );
                    },
                  ))
            ])));
  }

这是我的下拉菜单,其中包含标题名称:

//Drop down
  String _filterDropdown;

  List _dropdownList = [];
  List<DropdownMenuItem<String>> _dropDownMenuItems;

  List<DropdownMenuItem<String>> buildAndGetDropDownMenuItems(List tempList) {
    List<DropdownMenuItem<String>> items = List();
    for (String x in tempList) {
      items.add(DropdownMenuItem(
          value: x,
          child: Text(
            x,
            style: TextStyle(
                fontSize: 14,
                fontFamily: 'Roboto-Regular',
                fontWeight: FontWeight.w700,
                color: bPurple),
          )));
    }

    return items;
  }

并且在点击时将所有标题更改为下一个类别的选项卡栏

   TabBar(
                    onTap: _changedDropDownItem,
                    indicatorColor: bGreen,
                    labelColor: bPurple,
                    unselectedLabelColor: Colors.grey,
                    // isScrollable: true,
                    tabs: [
                      Tab(
                          icon: Icon(FontAwesomeIcons.medkit),
                          text: "Recovery"),
                      Tab(icon: Icon(FontAwesomeIcons.heart), text: "Feels"),
                      Tab(icon: Icon(Icons.info), text: "Product"),
                      Tab(
                        icon: Icon(FontAwesomeIcons.home),
                        text: "More",
                      ),
                    ],
                  ),

标签: flutterdartfilter

解决方案


请先试试这个:

void _changedDropDownItem(int newValue) {
    setState(() {
       makeDropdown(newValue);
      _selectedCustomerType = newValue;
    });

    // makeDropdown(newValue);

    print(_selectedCustomerType);
}

推荐阅读