首页 > 解决方案 > 如何在 Flutter 的导航抽屉中插入搜索选项

问题描述

我有一个 csv 文件,我正在使用下面的代码调用它的索引之一,其中包含德语单词。我想在我的抽屉中添加搜索选项,以便用户可以从此索引中搜索德语单词。我的整个代码都在一个类中,我也在其中调用Drawer

前进的最佳方式是什么。

new Container(
                                  child: new Text(
                                    csvTable[index+1][0],
                                    style: new TextStyle(
                                      fontSize: 24.0,
                                      color: Colors.black, ),),
                                  alignment: Alignment.center,
                                ),

标签: flutterdartsearchnavigation-drawer

解决方案


请检查以下代码。

TextEditingController txtCntSearch = TextEditingController();
  StreamController<String> isSearch = StreamController<String>();

  Stream get streamSearch => isSearch.stream;
  List<String> menuItems = ['A', 'AA', 'B', 'C', 'D', 'E', 'EE'];

  @override
  Widget build(BuildContext context) {
    return Material(
  child: Container(
    width: 300,
    color: Colors.white,
    child: Column(
      children: <Widget>[
        Expanded(
          child: TextFormField(controller: txtCntSearch, onFieldSubmitted: (data) {
            isSearch.add(txtCntSearch.value.text.trim());
          }, onChanged: (data){
            isSearch.add(txtCntSearch.value.text.trim());
          },),
        ),
        StreamBuilder(
          initialData: null,
          stream: streamSearch,
          builder: (c, s) {
            if (!s.hasData || s.data.toString().isEmpty) {
              // Here Show all menus Because search String is empty
              return Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: menuItems.map((e) => Text(e)).toList(),
                  ),
                ),
              );
            } else {
              // Here Filtered Item because here search string is not empty
              return Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children:
                        menuItems.map((e) => e.toLowerCase().contains(s.data.toString().toLowerCase()) ? Text(e) : SizedBox.shrink()).toList(),
                  ),
                ),
              );
            }
          },
        ),
      ],
    ),
  ),
);
  }

推荐阅读