【问题标题】:How to design Filters in Flutter?如何在 Flutter 中设计过滤器?
【发布时间】:2021-12-12 13:27:47
【问题描述】:

我是 Flutter 的新手,我想知道如何在 Flutter 中开发过滤器,例如 this(截图取自谷歌图片),所以我只想知道如何在 Flutter 中进行过滤,是否有类似插件或特殊的小部件?如果您提供任何参考或代码或任何教程将有助于我学习。谢谢你提前。

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies flutter-design


    【解决方案1】:

    你需要把它分解成几块。

    首先是您的 UI:这些只是标准的 Flutter 小部件。您希望用户向上滑动它吗?弄清楚如何通过向上滑动来显示 Widget。您希望它出现在警报弹出窗口中吗?弄清楚如何弹出警报。过滤器 UI 与任何其他 UI 没有什么不同 - 因此您可以查找并提出通用 UI 问题。

    其次是你如何实现模型。它可以是一些简单的东西,例如保存您获取的项目列表的 Provider;然后每个过滤器将更多 where 条件添加到您的列表中。

    类似:

    var items=<Item>[]; // somehow you would fetch the initial list of items
    var filtered;
    
    
    void addColorFilter(Color color) {
      filtered=filtered??items;
      filtered=filtered.where( (element) => element.color==color);
      notifyListeners();
    }
    
    
    void addSizeFilter(String size) {
      filtered=filtered??items;
      filtered=filtered.where( (element) => element.size==size);
      notifyListeners();
    }
    
    void removeFilters() => filtered=null;
    
    void getFiltered() => filtered??items;
    
    

    然后您可以在 ListView.builder() 中使用 filtered 迭代器来仅显示过滤后的项目。

    在这里回答您的后续问题:

    您有“AND”和“OR”条件的混合。如果您只是像上面那样继续添加迭代器,您将无法显示 2 种尺寸(M 和 S) - 因为没有项目同时是 M 和 S。在这种情况下,如果有一个多项选择过滤器,您将需要为可以有多项选择的每个过滤器类型添加附加列表。而且您将不得不重建整个过滤器。

    这可能是一个很好的起点 - 以您的价格和尺寸为例:

    var items=<Item>[]; // somehow you would fetch the initial list of items
    Iterator? filtered;
    
    double? lowPrice;
    void addLowPrice(double price) {
      lowPrice=price;
      rebuildFilter();
    }
    
    double? highPrice;
    void addHighPrice(double price) {
      highPrice=price;
      rebuildFilter();
    }
    
    var sizeOptions=<String>[];
    void addSizeFilter(String size) {
      sizeOptions.add(size);
      reubuildFilter();
    }
    
    void rebuildFilter() {
    
      filtered=items.where((e) => e.price>=lowPrice??0 && e.price<=highPrice&&double.infinity).where((e) => sizeOptions.isNotEmpty && sizeOptions.contains(e));
      
      notifyListeners();
    }
    
    void removeFilters() {
      lowPrice=null;
      highPrice=null;
      sizeOptions.clear();
      filtered=null;
    
      notifyListeners();
    }
    
    void getFiltered() => filtered??items;
    
    

    【讨论】:

    • 哇,@Andrija,但是我如何才能显示 范围 介于某个价格(78 美元 - 180 美元)之间的项目以及多个选择,例如我想同时显示 'M' 和 'S' 尺寸?
    • 我更新了我的答案以包含这个
    猜你喜欢
    • 1970-01-01
    • 2021-07-15
    • 2019-10-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2018-07-18
    • 2021-11-03
    相关资源
    最近更新 更多