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"
];
復制代碼

效果:

 

一起學習,一起成長!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM