【问题标题】:Search bar with ListView possible in Flutter?在 Flutter 中可以使用 ListView 的搜索栏吗?
【发布时间】:2023-03-06 09:39:02
【问题描述】:

我想在我的 Flutter 应用程序中实现一个搜索栏。我必须通过 ListTiles 中的列表视图。在这里,我想检查 listtile 的标题是否包含搜索字段中的字母。这可能与列表吗? 它不必与标题。它可能是我可以识别瓷砖的其他东西。但是请不要索引,用户不会知道它。 列表是正确的小部件还是我必须使用其他东西在我的应用程序中实现搜索引擎

【问题讨论】:

    标签: list flutter searchbar


    【解决方案1】:

    你可以使用原生的showSearch()函数,而不是使用第三方包:

    showSearch(context: context, delegate: ListSearchDelegate());
    

    然后是一个扩展SearchDelegate的类:

    class ListSearchDelegate extends SearchDelegate{
    
      ListSearchDelegate({Key key,}): super() ;
    
      List<String> listItems = <String>['One', 'Two', 'Three', 'Four', 'Five'] ;
    
      @override
      List<Widget> buildActions(BuildContext context) {
    
        return [
          IconButton(
            icon: Icon(Icons.clear),
            onPressed: () {
              query = '';
            },
          ),
        ];
      }
    
      @override
      Widget buildLeading(BuildContext context) {
        return IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () {
            close(context, null);
          },
        );
      }
    
      @override
      Widget buildResults(BuildContext context) {
    
        List<String> subList ;
    
        subList = query != '' ? listItems.where((item) => item.contains(query)).toList() : 
          listItems ;
    
        return ListView.builder(
            itemCount: subList.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(subList[index]),
              );
            }
        );
      }
    
      @override
      Widget buildSuggestions(BuildContext context) {
        return Container();
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      试试https://pub.dev/packages/flutter_search_panel

      List<SearchItem<int>> data = [
        SearchItem(0, 'This'),
        SearchItem(1, 'is'),
        SearchItem(2, 'a'),
        SearchItem(3, 'test'),
        SearchItem(4, '.'),
      ];
      
      FlutterSearchPanel<int>(
        padding: EdgeInsets.all(10.0),
        selected: 3,
        title: 'Demo Search Page',
        data: data,
        icon: new Icon(Icons.check_circle, color: Colors.white),
        color: Colors.blue,
        textStyle: new TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0, decorationStyle: TextDecorationStyle.dotted),
        onChanged: (int value) {
          print(value);
        },
      ),
      

      【讨论】:

        猜你喜欢
        • 2021-02-13
        • 2020-03-13
        • 1970-01-01
        • 2020-08-12
        • 2021-07-24
        • 2021-05-28
        • 1970-01-01
        • 1970-01-01
        • 2020-10-08
        相关资源
        最近更新 更多