首页 > 解决方案 > 如何在 Flutter 中使用 SearchDelegate 打开一个新页面

问题描述

我目前正在我的颤振应用程序中开发搜索功能。搜索功能起作用并在 ListTile 中显示结果。但我想导航到 ListTile 中显示的每个结果的特定页面。如果我在 ListTile 中使用 onTap 函数,如何将结果与其特定页面相匹配?

这是我的字符串列表:

final testList = [
  'test 1',
  'test 2',
  'test 3',
  'test 4',
];

我使用 SearchDelegate 来搜索结果:

 @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
          onPressed: () {
            query = '';
          },
          icon: Icon(Icons.clear)),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        onPressed: () {
          close(context, null);
        },
        icon: AnimatedIcon(
            icon: AnimatedIcons.menu_arrow, progress: transitionAnimation));
  }

  @override
  Widget buildResults(BuildContext context) {
    return Container(
      height: 100,
      width: 100,
      child: Card(
        color: Colors.red,
        child: Center(child: Text(query),),
      ),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? testList
        : testList.where((p) => p.startsWith(query)).toList();

    return ListView.builder(
      itemBuilder: (context, index) => ListTile(
        tileColor: backGround,
        onTap: () {
          showResults(context);
        },),
      itemCount: suggestionList.length,
    );
  }
}

标签: fluttersearchnavigation

解决方案


推荐阅读