Flutter showSearch 与 AnimatedIcon 的使用

5,732 阅读2分钟

Flutter 搜索页实现

在一般的 App 页面,可能都需要搜索功能,常见的就是在主页上面有一个搜索栏,点击会跳转到一个搜索页面。

在 flutter 中,也有这样的功能实现,主要是通过 showSearch 就能跳转到一个搜索页面。接下来看一下如何实现。

1、自定义 SearchDelegate

使用 flutter 提供的搜索页面,需要继承 SearchDelegate 实现自己的 Delegate。 SearchDelegate 提供了一些方法需要我们自己重写来实现我们自己的功能。

  • buildActions 显示在最右边的图标列表。
  • buildLeading 搜索栏左边的图标,一般都是返回。
  • buildResults 这个回调里进行搜索和并返回自己的搜索结果。
  • buildSuggestions 返回建议搜索结果。

示例:

class SearchBarViewDelegate extends SearchDelegate<String>{

  String searchHint = "请输入搜索内容...";
   var sourceList = [
    "dart",
    "dart 入门",
    "flutter",
    "flutter 编程",
    "flutter 编程开发",
  ];

  var  suggestList = [
    "flutter",
    "flutter 编程开发"
  ];


   @override
  String get searchFieldLabel => searchHint;


  @override
  List<Widget> buildActions(BuildContext context) {

    ///显示在最右边的控件列表
    return [

    IconButton(
      icon: Icon(Icons.clear),
      onPressed: (){
        query = "";

        ///搜索建议的内容
        showSuggestions(context);
        },
    ),
      IconButton(
          icon: Icon(Icons.search),
          onPressed: ()=>query = "",
      )
    ];
  }


  ///左侧带动画的控件,一般都是返回
  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: AnimatedIcon(icon: AnimatedIcons.menu_arrow, progress: transitionAnimation
        ),
        ///调用 close 关闭 search 界面
        onPressed: ()=>close(context,null),
    );
  }


  ///展示搜索结果
  @override
  Widget buildResults(BuildContext context) {

    List<String> result = List();

    ///模拟搜索过程
    for (var str in sourceList){
      ///query 就是输入框的 TextEditingController
      if (query.isNotEmpty && str.contains(query)){
          result.add(str);
      }
    }

    ///展示搜索结果
    return ListView.builder(
      itemCount: result.length,
      itemBuilder: (BuildContext context, int index)=>ListTile(
        title: Text(result[index]),
      ),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {

    List<String> suggest = query.isEmpty ? suggestList : sourceList.where((input)=>input.startsWith(query)).toList();
    return ListView.builder(
        itemCount: suggest.length,
        itemBuilder: (BuildContext context, int index)=>
    InkWell(
      child:         ListTile(
        title: RichText(
          text: TextSpan(
            text: suggest[index].substring(0, query.length),
            style: TextStyle(color: Colors.blue,fontWeight: FontWeight.bold),
            children: [
              TextSpan(
                text: suggest[index].substring(query.length),
                style: TextStyle(color: Colors.grey),
              ),
            ],
          ),
        ),
      ),
        onTap: (){
       //  query.replaceAll("", suggest[index].toString());
          searchHint = "";
          query =  suggest[index].toString();
         showResults(context);
        },
    ),


    );
  }
}

2、使用自定义 SearchBarViewDelegate 展现搜索页面

    IconButton(
              icon: Icon(Icons.search),
              onPressed: (){
                showSearch(context: context, delegate: SearchBarViewDelegate());
              }
          )

效果:

Flutter AnimatedIcon

在 flutter 中也提供一一种 widiget —— AnimatedIcon 来展示带动画的 Icon,可以带来很好的用户体验。在上面的搜索栏中,返回按钮用的就是这个 widget。

并不是所有的 Icon 都能展示这种效果,flutter 中,提供的 AnimatedIcons 一共有如下这些:

abstract class AnimatedIcons {

  /// The material design add to event icon animation.
  static const AnimatedIconData add_event = _$add_event;

  /// The material design arrow to menu icon animation.
  static const AnimatedIconData arrow_menu = _$arrow_menu;

  /// The material design close to menu icon animation.
  static const AnimatedIconData close_menu = _$close_menu;

  /// The material design ellipsis to search icon animation.
  static const AnimatedIconData ellipsis_search = _$ellipsis_search;

  /// The material design event to add icon animation.
  static const AnimatedIconData event_add = _$event_add;

  /// The material design home to menu icon animation.
  static const AnimatedIconData home_menu = _$home_menu;

  /// The material design list to view icon animation.
  static const AnimatedIconData list_view = _$list_view;

  /// The material design menu to arrow icon animation.
  static const AnimatedIconData menu_arrow = _$menu_arrow;

  /// The material design menu to close icon animation.
  static const AnimatedIconData menu_close = _$menu_close;

  /// The material design menu to home icon animation.
  static const AnimatedIconData menu_home = _$menu_home;

  /// The material design pause to play icon animation.
  static const AnimatedIconData pause_play = _$pause_play;

  /// The material design play to pause icon animation.
  static const AnimatedIconData play_pause = _$play_pause;

  /// The material design search to ellipsis icon animation.
  static const AnimatedIconData search_ellipsis = _$search_ellipsis;

  /// The material design view to list icon animation.
  static const AnimatedIconData view_list = _$view_list;
}

使用步骤

1、定义 AnimationController 控制动画

    controller = AnimationController(vsync: this)
      ..drive(Tween(begin: 0, end: 1))
      ..duration = Duration(milliseconds: 500);

2、 AnimatedIcon 指定动画控制器和需要展示的动画Icon

     AnimatedIcon(
        icon: AnimatedIcons.play_pause,
        progress: controller,
        size: 35,
        semanticLabel: "play_pause",
      ),

3、控制播放

     InkWell(
                child:   _icons[index],

           onTap: () {
                  if (controller.status == AnimationStatus.completed) {
                    controller.reverse();
                  } else if (controller.status == AnimationStatus.dismissed) {
                    controller.forward();
                  }
                },
              ),

效果:

github

最后

欢迎关注「Flutter 编程开发」微信公众号 。