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

https://www.jianshu.com/p/63aca25a463c

https://www.cnblogs.com/loaderman/p/11350306.html

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

  • List<Widget> buildActions(BuildContext context):这个方法返回一个控件列表,显示为搜索框右边的图标按钮,这里设置为一个清除按钮,并且在搜索内容为空的时候显示建议搜索内容,使用的是showSuggestions(context)方法:
@override
List<Widget> buildActions(BuildContext context) {
  return [
    IconButton(
      icon: Icon(Icons.clear),
      onPressed: () {
        query = "";
        showSuggestions(context);
      },
    ),
  ];
}
  • showSuggestions(context):这个方法显示建议的搜索内容,也就是Widget buildSuggestions(BuildContext context)方法的的调用;

  • Widget buildLeading(BuildContext 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);
      }
    },
  );
}
  • Widget buildSuggestions(BuildContext context):这个方法返回一个控件,显示为搜索内容区域的建议内容。
  • Widget buildSuggestions(BuildContext context):这个方法返回一个控件,显示为搜索内容区域的搜索结果内容。
  • ThemeData appBarTheme(BuildContext 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()):跳转到搜索界面。



作者:我爱小白小白爱大开
链接:https://www.jianshu.com/p/63aca25a463c
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

 

 

flutter 中的搜索条实现

复制代码
import 'package:flutter/material.dart';
import 'package:flutter_app/SearchBarDemo.dart';



void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,  //定义主题风格    primarySwatch
      ),
      home:  SearchBarDemo(),
    );
  }

}
复制代码
复制代码
import 'package:flutter/material.dart';
import 'asset.dart';

class SearchBarDemo extends StatefulWidget {
  _SearchBarDemoState createState() => _SearchBarDemoState();
}

class _SearchBarDemoState extends State<SearchBarDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('SearchBarDemo'), actions: <Widget>[
      IconButton(
          icon: Icon(Icons.search),
          onPressed: () {
            showSearch(context: context, delegate: searchBarDelegate());
          }
          // showSearch(context:context,delegate: searchBarDelegate()),
          ),
    ]));
  }
}

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

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

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

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? recentSuggest
        : searchList.where((input) => input.startsWith(query)).toList();
    return ListView.builder(
        itemCount: suggestionList.length,
        itemBuilder: (context, index) => ListTile(
              title: RichText(
                  text: TextSpan(
                      text: suggestionList[index].substring(0, query.length),
                      style: TextStyle(
                          color: Colors.black, fontWeight: FontWeight.bold),
                      children: [
                    TextSpan(
                        text: suggestionList[index].substring(query.length),
                        style: TextStyle(color: Colors.grey))
                  ])),
            ));
  }
}
复制代码
复制代码
const searchList = [
  "上衣",
  "华为",
  "电视",
  "新闻"
];

const recentSuggest = [
  "推荐-1",
  "推荐-2"
];
复制代码

效果:

 

一起学习,一起成长!

 

posted @ 2020-03-27 12:20  sundayswift  阅读(2830)  评论(0编辑  收藏  举报