Flutter圈子FlutterAndroid开发

Flutter搜索界面的实现,SearchDelegate的使用

2019-02-18  本文已影响6人  Ugly_K

Flutter 搜索界面的实现,SearchDelegate的使用

1.使用系统的搜索界面

在之前的学习中自己实现了了一个搜索界面,其中自定义了搜索栏,实现效果也就将就,后来发现在Flutter中有现成的控件可以使用,也就是SearchDelegate<T>,调用showSearch(context: context, delegate: searchBarDelegate())实现。

2.定义SearchDelegate

class searchBarDelegate extends SearchDelegate<String> {
  @override
  List<Widget> buildActions(BuildContext context) {
    return null;
  }

  @override
  Widget buildLeading(BuildContext context) {
    return null;
  }

  @override
  Widget buildResults(BuildContext context) {
    return null;
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return null;
  }


  @override
  ThemeData appBarTheme(BuildContext context) {
    // TODO: implement appBarTheme
    return super.appBarTheme(context);
  }
}

继承SearchDelegate<String>之后需要重写一些方法,这里给定的String类型是指搜索query的类型为String

@override
List<Widget> buildActions(BuildContext context) {
  return [
    IconButton(
      icon: Icon(Icons.clear),
      onPressed: () {
        query = "";
        showSuggestions(context);
      },
    ),
  ];
}
@override
Widget buildLeading(BuildContext context) {
  return IconButton(
    icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
    onPressed: () {
      if (query.isEmpty) {
        close(context, null);
      } else {
        query = "";
        showSuggestions(context);
      }
    },
  );
}
///  * [AppBar.backgroundColor], which is set to [ThemeData.primaryColor].
///  * [AppBar.iconTheme], which is set to [ThemeData.primaryIconTheme].
///  * [AppBar.textTheme], which is set to [ThemeData.primaryTextTheme].
///  * [AppBar.brightness], which is set to [ThemeData.primaryColorBrightness].
ThemeData appBarTheme(BuildContext context) {
  assert(context != null);
  final ThemeData theme = Theme.of(context);
  assert(theme != null);
  return theme.copyWith(
    primaryColor: Colors.white,
    primaryIconTheme: theme.primaryIconTheme.copyWith(color: Colors.grey),
    primaryColorBrightness: Brightness.light,
    primaryTextTheme: theme.textTheme,
  );
}

可以看到默认的的浅色主题白底灰字,可以自行修改;


建议搜索内容 搜索结果展示

3.调用showSearch(context: context, delegate: searchBarDelegate())方法跳转到搜索界面

showSearch(context: context, delegate: searchBarDelegate()):跳转到搜索界面。

上一篇下一篇

猜你喜欢

热点阅读