我想使用flutter中的checkboxlisttile过滤,但是当我使用警报对话框时,我没有在listView中显示任何过滤的反映?

发布于 2025-02-07 18:56:31 字数 15179 浏览 3 评论 0 原文

我将一个Litview Builder列表过滤到另一个复选框列表,但这在工作,但是当我在未显示过滤器反射时,在警报对话框中添加此checkboxlisttile时。

我也使用了状态布置器,但对过滤ListView没有用。

[这是第一个链接显示产品列表数据

https://run.mocky.io/v3/0595387E-732E-732E-47CF-9675-244FED9FC014” rel =“ nofollow noreferrer”

这是API链接

const String baseUrl = "https://run.mocky.io/v3/";
const String productDataUrl = baseUrl + "4ecbd2ea-a725-438b-b8fc-da8fc08bc875";
const String productCategoryDataUrl =
    baseUrl + "0595387e-732e-47cf-9675-244fed9fc014";

这是我们要过滤

的listView模型的产品模型类
class ProductDataModel {
  int? productId;
  String? productName;
  int? productPrice;
  int? productKG;
  String? productCategoryId;

  ProductDataModel(
      {this.productId,
      this.productName,
      this.productPrice,
      this.productKG,
      this.productCategoryId});

  ProductDataModel.fromJson(Map<String, dynamic> json) {
    productId = json['ProductId'];
    productName = json['ProductName'];
    productPrice = json['ProductPrice'];
    productKG = json['ProductKG'];
    productCategoryId = json['ProductCategoryId'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['ProductId'] = this.productId;
    data['ProductName'] = this.productName;
    data['ProductPrice'] = this.productPrice;
    data['ProductKG'] = this.productKG;
    data['ProductCategoryId'] = this.productCategoryId;
    return data;
  }
}

此productCategory模型类用于使用过滤器和此模型类 Checkbaxile

中的数据
class ProductCategoryDataModel {
  int? productCategoryId;
  String? productCategoryName;
  bool? isChecked=false;

  ProductCategoryDataModel(
      {this.productCategoryId, this.productCategoryName, this.isChecked});

  ProductCategoryDataModel.fromJson(Map<String, dynamic> json) {
    productCategoryId = json['ProductCategoryId'];
    productCategoryName = json['ProductCategoryName'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['ProductCategoryId'] = this.productCategoryId;
    data['ProductCategoryName'] = this.productCategoryName;
    return data;
  }
}

这是显示使用ListView和过滤数据的代码 checkboxlisttile在警报对话框中的数据。

import 'dart:convert';
import 'dart:developer';

import 'package:dummy_checkbox_filter_list/commons/api_url.dart';
import 'package:dummy_checkbox_filter_list/model/product_category_data_model.dart';
import 'package:dummy_checkbox_filter_list/model/product_data_model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<ProductDataModel> productDataList = [];
  Set<ProductDataModel> productDataListDisplay = {};
  List<ProductCategoryDataModel> productCategoryDataList = [];
  List<ProductCategoryDataModel> selectProductCategoryDataList = [];

  ScrollController scrollController = ScrollController();
  bool isShowLoader = false;

  getProductList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=> ${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productDataList.add(ProductDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  getProductCategoryList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productCategoryDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=>${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productCategoryDataList
              .add(new ProductCategoryDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productCategoryDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  @override
  void initState() {
    getProductList();
    getProductCategoryList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    filterProduct(productDataList);
    return Scaffold(
      body: SafeArea(
        child: isShowLoader == false
            ? SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return StatefulBuilder(
                                builder: (context, setState) {
                                  return AlertDialog(
                                    titlePadding: EdgeInsets.zero,
                                    backgroundColor: Color(0xFF242424),
                                    title: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        IconButton(
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                            icon: Icon(
                                              Icons.close,
                                              color: Colors.white,
                                              size: 25,
                                            ))
                                      ],
                                    ),
                                    contentPadding: EdgeInsets.zero,
                                    content: Container(
                                      padding: EdgeInsets.all(5),
                                      width: double.maxFinite,
                                      child: ListView(
                                        padding: EdgeInsets.all(8.0),
                                        children: [
                                          Text(
                                            "dfff "+productCategoryDataList[0].isChecked.toString(),
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 16),
                                          ),
                                          ...productCategoryDataList
                                              .map((e) => CheckboxListTile(
                                                    controlAffinity:
                                                        ListTileControlAffinity
                                                            .leading,
                                                    title: Text(
                                                      "${e.productCategoryName}",
                                                      style: TextStyle(
                                                          color: Colors.white,
                                                          fontSize: 16),
                                                    ),
                                                    value: e.isChecked,
                                                    selected:
                                                        selectProductCategoryDataList
                                                            .contains(e),
                                                    onChanged: (val) {
                                                      print("val: "+val.toString());
                                                      setState(() {

                                                        e.isChecked = val;
                                                        selectProductCategoryDataList
                                                                .contains(e)
                                                            ? selectProductCategoryDataList
                                                                .remove(e)
                                                            : selectProductCategoryDataList
                                                                .add(e);
                                                        print(
                                                            "_isChecked: ${e.isChecked}");
                                                      });
                                                    },
                                                  ))
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              );
                            });
                      },
                      style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                          onPrimary: Colors.white,
                          minimumSize: Size(
                              MediaQuery.of(context).size.width * 0.30,
                              MediaQuery.of(context).size.height * 0.05)),
                      child: Text(
                        "Filter",
                        style: TextStyle(fontSize: 15),
                      ),
                    ),
                  
                    Container(
                      child: ListView.builder(
                        itemCount: productDataListDisplay.length,
                        shrinkWrap: true,
                        controller: scrollController,
                        itemBuilder: (context, index) {
                          return Card(
                            child: Container(
                              padding: EdgeInsets.only(top: 15, bottom: 15),
                              color: (index % 2 == 0)
                                  ? Colors.grey.shade100
                                  : Colors.white,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(productDataListDisplay
                                      .elementAt(index)
                                      .productId
                                      .toString()),
                                  Center(
                                    child: Text(
                                      productDataListDisplay
                                          .elementAt(index)
                                          .productName
                                          .toString(),
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productKG.toString()} KG",
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              )
            : Center(
                child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
              ),
      ),
    );
  }

  void filterProduct(allProducts) {
    productDataListDisplay.clear();
    if (selectProductCategoryDataList != null &&
        selectProductCategoryDataList.isNotEmpty) {
      final List<int> idsOfSelectedCategories = selectProductCategoryDataList
          .map((category) => category.productCategoryId!)
          .toList();
      print("idsOfSelectedCategories=> $idsOfSelectedCategories");
      Set<ProductDataModel> storesInSelectedCategories =
          getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
      setState(() {
        productDataListDisplay.addAll(storesInSelectedCategories);
        print(allProducts.length);
        print(storesInSelectedCategories.length);
      });

    } else {
      setState(() {
        productDataListDisplay.addAll(allProducts);
      });
    }
  }

  Set<ProductDataModel> getStoresFromSelectedCategories(
      List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
    Set<ProductDataModel> allProductsFromCategory = {};

    for (var categoryId in idsOfSelectedCategories) {
      var productMatched = allProducts
          .where((store) => store.productCategoryId!
              .split(" ")
              .contains(categoryId.toString()))
          .toList();
      print("Stores Matched runtime=>${productMatched.runtimeType}");
      allProductsFromCategory.addAll(productMatched);
    }
    return allProductsFromCategory;
  }
}

I filter the one litview builder list to another checkbox list and this is working, but when i add this CheckboxListTile in Alert dialog when no filter reflection showing.

I used StatefulBuilder also but is not useful to filtering listview.

[This is first link to show Product list data][1]

This is second link of filter list

This is Listview data image that i want to filter.

This is CHeckBoxTileList image this data is in Alert dialog box

I am stuck in how to one data filter to another item filter that availiable in Alert dialog.

This is Api link

const String baseUrl = "https://run.mocky.io/v3/";
const String productDataUrl = baseUrl + "4ecbd2ea-a725-438b-b8fc-da8fc08bc875";
const String productCategoryDataUrl =
    baseUrl + "0595387e-732e-47cf-9675-244fed9fc014";

This is product model class that listview model that we want to filter

class ProductDataModel {
  int? productId;
  String? productName;
  int? productPrice;
  int? productKG;
  String? productCategoryId;

  ProductDataModel(
      {this.productId,
      this.productName,
      this.productPrice,
      this.productKG,
      this.productCategoryId});

  ProductDataModel.fromJson(Map<String, dynamic> json) {
    productId = json['ProductId'];
    productName = json['ProductName'];
    productPrice = json['ProductPrice'];
    productKG = json['ProductKG'];
    productCategoryId = json['ProductCategoryId'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['ProductId'] = this.productId;
    data['ProductName'] = this.productName;
    data['ProductPrice'] = this.productPrice;
    data['ProductKG'] = this.productKG;
    data['ProductCategoryId'] = this.productCategoryId;
    return data;
  }
}

This ProductCategory Model class for using filter and this model class
data in CheckboxTile

class ProductCategoryDataModel {
  int? productCategoryId;
  String? productCategoryName;
  bool? isChecked=false;

  ProductCategoryDataModel(
      {this.productCategoryId, this.productCategoryName, this.isChecked});

  ProductCategoryDataModel.fromJson(Map<String, dynamic> json) {
    productCategoryId = json['ProductCategoryId'];
    productCategoryName = json['ProductCategoryName'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['ProductCategoryId'] = this.productCategoryId;
    data['ProductCategoryName'] = this.productCategoryName;
    return data;
  }
}

This is code of showing listview and filter data using
checkboxlisttile that data in Alert dialog .

import 'dart:convert';
import 'dart:developer';

import 'package:dummy_checkbox_filter_list/commons/api_url.dart';
import 'package:dummy_checkbox_filter_list/model/product_category_data_model.dart';
import 'package:dummy_checkbox_filter_list/model/product_data_model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<ProductDataModel> productDataList = [];
  Set<ProductDataModel> productDataListDisplay = {};
  List<ProductCategoryDataModel> productCategoryDataList = [];
  List<ProductCategoryDataModel> selectProductCategoryDataList = [];

  ScrollController scrollController = ScrollController();
  bool isShowLoader = false;

  getProductList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=> ${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productDataList.add(ProductDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  getProductCategoryList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productCategoryDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=>${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productCategoryDataList
              .add(new ProductCategoryDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productCategoryDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  @override
  void initState() {
    getProductList();
    getProductCategoryList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    filterProduct(productDataList);
    return Scaffold(
      body: SafeArea(
        child: isShowLoader == false
            ? SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return StatefulBuilder(
                                builder: (context, setState) {
                                  return AlertDialog(
                                    titlePadding: EdgeInsets.zero,
                                    backgroundColor: Color(0xFF242424),
                                    title: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        IconButton(
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                            icon: Icon(
                                              Icons.close,
                                              color: Colors.white,
                                              size: 25,
                                            ))
                                      ],
                                    ),
                                    contentPadding: EdgeInsets.zero,
                                    content: Container(
                                      padding: EdgeInsets.all(5),
                                      width: double.maxFinite,
                                      child: ListView(
                                        padding: EdgeInsets.all(8.0),
                                        children: [
                                          Text(
                                            "dfff "+productCategoryDataList[0].isChecked.toString(),
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 16),
                                          ),
                                          ...productCategoryDataList
                                              .map((e) => CheckboxListTile(
                                                    controlAffinity:
                                                        ListTileControlAffinity
                                                            .leading,
                                                    title: Text(
                                                      "${e.productCategoryName}",
                                                      style: TextStyle(
                                                          color: Colors.white,
                                                          fontSize: 16),
                                                    ),
                                                    value: e.isChecked,
                                                    selected:
                                                        selectProductCategoryDataList
                                                            .contains(e),
                                                    onChanged: (val) {
                                                      print("val: "+val.toString());
                                                      setState(() {

                                                        e.isChecked = val;
                                                        selectProductCategoryDataList
                                                                .contains(e)
                                                            ? selectProductCategoryDataList
                                                                .remove(e)
                                                            : selectProductCategoryDataList
                                                                .add(e);
                                                        print(
                                                            "_isChecked: ${e.isChecked}");
                                                      });
                                                    },
                                                  ))
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              );
                            });
                      },
                      style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                          onPrimary: Colors.white,
                          minimumSize: Size(
                              MediaQuery.of(context).size.width * 0.30,
                              MediaQuery.of(context).size.height * 0.05)),
                      child: Text(
                        "Filter",
                        style: TextStyle(fontSize: 15),
                      ),
                    ),
                  
                    Container(
                      child: ListView.builder(
                        itemCount: productDataListDisplay.length,
                        shrinkWrap: true,
                        controller: scrollController,
                        itemBuilder: (context, index) {
                          return Card(
                            child: Container(
                              padding: EdgeInsets.only(top: 15, bottom: 15),
                              color: (index % 2 == 0)
                                  ? Colors.grey.shade100
                                  : Colors.white,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(productDataListDisplay
                                      .elementAt(index)
                                      .productId
                                      .toString()),
                                  Center(
                                    child: Text(
                                      productDataListDisplay
                                          .elementAt(index)
                                          .productName
                                          .toString(),
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productKG.toString()} KG",
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              )
            : Center(
                child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
              ),
      ),
    );
  }

  void filterProduct(allProducts) {
    productDataListDisplay.clear();
    if (selectProductCategoryDataList != null &&
        selectProductCategoryDataList.isNotEmpty) {
      final List<int> idsOfSelectedCategories = selectProductCategoryDataList
          .map((category) => category.productCategoryId!)
          .toList();
      print("idsOfSelectedCategories=> $idsOfSelectedCategories");
      Set<ProductDataModel> storesInSelectedCategories =
          getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
      setState(() {
        productDataListDisplay.addAll(storesInSelectedCategories);
        print(allProducts.length);
        print(storesInSelectedCategories.length);
      });

    } else {
      setState(() {
        productDataListDisplay.addAll(allProducts);
      });
    }
  }

  Set<ProductDataModel> getStoresFromSelectedCategories(
      List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
    Set<ProductDataModel> allProductsFromCategory = {};

    for (var categoryId in idsOfSelectedCategories) {
      var productMatched = allProducts
          .where((store) => store.productCategoryId!
              .split(" ")
              .contains(categoryId.toString()))
          .toList();
      print("Stores Matched runtime=>${productMatched.runtimeType}");
      allProductsFromCategory.addAll(productMatched);
    }
    return allProductsFromCategory;
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心意如水 2025-02-14 18:56:31

添加.then((value){if(已挂载){setState((){});}});为了显示示例,以便在AlertDialog关闭时,状态会刷新。

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<ProductDataModel> productDataList = [];
  Set<ProductDataModel> productDataListDisplay = {};
  List<ProductCategoryDataModel> productCategoryDataList = [];
  List<ProductCategoryDataModel> selectProductCategoryDataList = [];

  ScrollController scrollController = ScrollController();
  bool isShowLoader = false;

  getProductList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=> ${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productDataList.add(ProductDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  getProductCategoryList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productCategoryDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=>${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productCategoryDataList
              .add(new ProductCategoryDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productCategoryDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  @override
  void initState() {
    getProductList();
    getProductCategoryList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    filterProduct(productDataList);
    return Scaffold(
      body: SafeArea(
        child: isShowLoader == false
            ? SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return StatefulBuilder(
                                builder: (context, setState) {
                                  return AlertDialog(
                                    titlePadding: EdgeInsets.zero,
                                    backgroundColor: const Color(0xFF242424),
                                    title: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        IconButton(
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                            icon: const Icon(
                                              Icons.close,
                                              color: Colors.white,
                                              size: 25,
                                            ))
                                      ],
                                    ),
                                    contentPadding: EdgeInsets.zero,
                                    content: Container(
                                      padding: EdgeInsets.all(5),
                                      width: double.maxFinite,
                                      child: ListView(
                                        padding: EdgeInsets.all(8.0),
                                        children: [
                                          Text(
                                            "dfff ${productCategoryDataList[0].isChecked}",
                                            style: const TextStyle(
                                                color: Colors.white,
                                                fontSize: 16),
                                          ),
                                          ...productCategoryDataList
                                              .map((e) => CheckboxListTile(
                                                    controlAffinity:
                                                        ListTileControlAffinity
                                                            .leading,
                                                    title: Text(
                                                      "${e.productCategoryName}",
                                                      style: const TextStyle(
                                                          color: Colors.white,
                                                          fontSize: 16),
                                                    ),
                                                    value: e.isChecked,
                                                    selected:
                                                        selectProductCategoryDataList
                                                            .contains(e),
                                                    onChanged: (val) {
                                                      print("val: $val");
                                                      setState(() {
                                                        e.isChecked = val;
                                                        selectProductCategoryDataList
                                                                .contains(e)
                                                            ? selectProductCategoryDataList
                                                                .remove(e)
                                                            : selectProductCategoryDataList
                                                                .add(e);
                                                        print(
                                                            "_isChecked: ${e.isChecked}");
                                                      });
                                                    },
                                                  ))
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              );
                            }).then((value) {
                          if (mounted) {
                            setState(() {});
                          }
                        });
                      },
                      style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                          onPrimary: Colors.white,
                          minimumSize: Size(
                              MediaQuery.of(context).size.width * 0.30,
                              MediaQuery.of(context).size.height * 0.05)),
                      child: const Text(
                        "Filter",
                        style: TextStyle(fontSize: 15),
                      ),
                    ),
                    Container(
                      child: ListView.builder(
                        itemCount: productDataListDisplay.length,
                        shrinkWrap: true,
                        controller: scrollController,
                        itemBuilder: (context, index) {
                          return Card(
                            child: Container(
                              padding: EdgeInsets.only(top: 15, bottom: 15),
                              color: (index % 2 == 0)
                                  ? Colors.grey.shade100
                                  : Colors.white,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(productDataListDisplay
                                      .elementAt(index)
                                      .productId
                                      .toString()),
                                  Center(
                                    child: Text(
                                      productDataListDisplay
                                          .elementAt(index)
                                          .productName
                                          .toString(),
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productKG.toString()} KG",
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              )
            : Center(
                child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
              ),
      ),
    );
  }

  void filterProduct(allProducts) {
    productDataListDisplay.clear();
    if (selectProductCategoryDataList != null &&
        selectProductCategoryDataList.isNotEmpty) {
      final List<int> idsOfSelectedCategories = selectProductCategoryDataList
          .map((category) => category.productCategoryId!)
          .toList();
      print("idsOfSelectedCategories=> $idsOfSelectedCategories");
      Set<ProductDataModel> storesInSelectedCategories =
          getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
      setState(() {
        productDataListDisplay.addAll(storesInSelectedCategories);
        print(allProducts.length);
        print(storesInSelectedCategories.length);
      });
    } else {
      setState(() {
        productDataListDisplay.addAll(allProducts);
      });
    }
  }

  Set<ProductDataModel> getStoresFromSelectedCategories(
      List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
    Set<ProductDataModel> allProductsFromCategory = {};

    for (var categoryId in idsOfSelectedCategories) {
      var productMatched = allProducts
          .where((store) => store.productCategoryId!
              .split(" ")
              .contains(categoryId.toString()))
          .toList();
      print("Stores Matched runtime=>${productMatched.runtimeType}");
      allProductsFromCategory.addAll(productMatched);
    }
    return allProductsFromCategory;
  }
}

Add .then((value) {if (mounted) {setState(() {});}}); to showdialog so that state gets refreshed when alertdialog closes.

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<ProductDataModel> productDataList = [];
  Set<ProductDataModel> productDataListDisplay = {};
  List<ProductCategoryDataModel> productCategoryDataList = [];
  List<ProductCategoryDataModel> selectProductCategoryDataList = [];

  ScrollController scrollController = ScrollController();
  bool isShowLoader = false;

  getProductList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=> ${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productDataList.add(ProductDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  getProductCategoryList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productCategoryDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=>${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productCategoryDataList
              .add(new ProductCategoryDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productCategoryDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  @override
  void initState() {
    getProductList();
    getProductCategoryList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    filterProduct(productDataList);
    return Scaffold(
      body: SafeArea(
        child: isShowLoader == false
            ? SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return StatefulBuilder(
                                builder: (context, setState) {
                                  return AlertDialog(
                                    titlePadding: EdgeInsets.zero,
                                    backgroundColor: const Color(0xFF242424),
                                    title: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        IconButton(
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                            icon: const Icon(
                                              Icons.close,
                                              color: Colors.white,
                                              size: 25,
                                            ))
                                      ],
                                    ),
                                    contentPadding: EdgeInsets.zero,
                                    content: Container(
                                      padding: EdgeInsets.all(5),
                                      width: double.maxFinite,
                                      child: ListView(
                                        padding: EdgeInsets.all(8.0),
                                        children: [
                                          Text(
                                            "dfff ${productCategoryDataList[0].isChecked}",
                                            style: const TextStyle(
                                                color: Colors.white,
                                                fontSize: 16),
                                          ),
                                          ...productCategoryDataList
                                              .map((e) => CheckboxListTile(
                                                    controlAffinity:
                                                        ListTileControlAffinity
                                                            .leading,
                                                    title: Text(
                                                      "${e.productCategoryName}",
                                                      style: const TextStyle(
                                                          color: Colors.white,
                                                          fontSize: 16),
                                                    ),
                                                    value: e.isChecked,
                                                    selected:
                                                        selectProductCategoryDataList
                                                            .contains(e),
                                                    onChanged: (val) {
                                                      print("val: $val");
                                                      setState(() {
                                                        e.isChecked = val;
                                                        selectProductCategoryDataList
                                                                .contains(e)
                                                            ? selectProductCategoryDataList
                                                                .remove(e)
                                                            : selectProductCategoryDataList
                                                                .add(e);
                                                        print(
                                                            "_isChecked: ${e.isChecked}");
                                                      });
                                                    },
                                                  ))
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              );
                            }).then((value) {
                          if (mounted) {
                            setState(() {});
                          }
                        });
                      },
                      style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                          onPrimary: Colors.white,
                          minimumSize: Size(
                              MediaQuery.of(context).size.width * 0.30,
                              MediaQuery.of(context).size.height * 0.05)),
                      child: const Text(
                        "Filter",
                        style: TextStyle(fontSize: 15),
                      ),
                    ),
                    Container(
                      child: ListView.builder(
                        itemCount: productDataListDisplay.length,
                        shrinkWrap: true,
                        controller: scrollController,
                        itemBuilder: (context, index) {
                          return Card(
                            child: Container(
                              padding: EdgeInsets.only(top: 15, bottom: 15),
                              color: (index % 2 == 0)
                                  ? Colors.grey.shade100
                                  : Colors.white,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(productDataListDisplay
                                      .elementAt(index)
                                      .productId
                                      .toString()),
                                  Center(
                                    child: Text(
                                      productDataListDisplay
                                          .elementAt(index)
                                          .productName
                                          .toString(),
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productKG.toString()} KG",
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              )
            : Center(
                child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
              ),
      ),
    );
  }

  void filterProduct(allProducts) {
    productDataListDisplay.clear();
    if (selectProductCategoryDataList != null &&
        selectProductCategoryDataList.isNotEmpty) {
      final List<int> idsOfSelectedCategories = selectProductCategoryDataList
          .map((category) => category.productCategoryId!)
          .toList();
      print("idsOfSelectedCategories=> $idsOfSelectedCategories");
      Set<ProductDataModel> storesInSelectedCategories =
          getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
      setState(() {
        productDataListDisplay.addAll(storesInSelectedCategories);
        print(allProducts.length);
        print(storesInSelectedCategories.length);
      });
    } else {
      setState(() {
        productDataListDisplay.addAll(allProducts);
      });
    }
  }

  Set<ProductDataModel> getStoresFromSelectedCategories(
      List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
    Set<ProductDataModel> allProductsFromCategory = {};

    for (var categoryId in idsOfSelectedCategories) {
      var productMatched = allProducts
          .where((store) => store.productCategoryId!
              .split(" ")
              .contains(categoryId.toString()))
          .toList();
      print("Stores Matched runtime=>${productMatched.runtimeType}");
      allProductsFromCategory.addAll(productMatched);
    }
    return allProductsFromCategory;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文