how to create toolbar searchview in flutter

前端 未结 6 1291
不思量自难忘°
不思量自难忘° 2020-12-02 13:19

i need to implement searchview in toolbar my app to achieve list view list filter. like below image, i searched lot still not get proper answer. Any help will be appreciated

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 14:26

    You should use SearchDelegate which comes out of the box with Flutter. Here is a small video how it works:


    Full solution:

    class SearchPage extends StatefulWidget {
      @override
      _SearchPageState createState() => _SearchPageState();
    }
    
    class _SearchPageState extends State {
      String _result;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("Search")),
          body: Center(
            child: Column(
              children: [
                Text(_result ?? "", style: TextStyle(fontSize: 18)),
                RaisedButton(
                  onPressed: () async {
                    var result = await showSearch(
                      context: context,
                      delegate: CustomDelegate(),
                    );
                    setState(() {
                      _result = result;
                    });
                  },
                  child: Text("Search"),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    class CustomDelegate extends SearchDelegate {
      List data = nouns.take(100).toList();
    
      @override
      List buildActions(BuildContext context) => [IconButton(icon: Icon(Icons.clear), onPressed: () => query = '')];
    
      @override
      Widget buildLeading(BuildContext context) => IconButton(icon: Icon(Icons.chevron_left), onPressed: () => close(context, null));
    
      @override
      Widget buildResults(BuildContext context) => Container();
    
      @override
      Widget buildSuggestions(BuildContext context) {
        var listToShow;
        if (query.isNotEmpty)
          listToShow = data.where((e) => e.contains(query) && e.startsWith(query)).toList();
        else
          listToShow = data;
    
        return ListView.builder(
          itemCount: listToShow.length,
          itemBuilder: (_, i) {
            var noun = listToShow[i];
            return ListTile(
              title: Text(noun),
              onTap: () => close(context, noun),
            );
          },
        );
      }
    }
    

提交回复
热议问题