博客地址:html
https://jspang.com/post/flutterDemo.html#toc-1b4數組
視頻地址:https://www.bilibili.com/video/av39709290/?p=11app
繼承SearhDelegate 並複寫裏面的方法less
須要複寫裏面的四個方法。咱們定義類:searchBarDelegatejsp
重寫的第一個方法:buildActions 就是搜索的時候右邊的差號。裏面接收 一個上下文。通常咱們返回一個IconButtonide
query就是咱們搜索的參數。咱們設置爲空。post
點擊事件,一點擊的時候就把搜索內容設置爲空字體
複寫第二個方法:就是最左側咱們返回的箭頭ui
下圖中的build單詞拼錯了後續已經改正過來spa
再重寫咱們的搜索結果:buildResults
咱們返回Container容器。child裏面放Card組件,爲了讓搜索結果好看一點
爲了Card卡片變得好看一些,咱們給它一個亮紅色
再重寫最重要的一個方法:
用戶一邊搜索通常提示用戶的內容;
這裏咱們採用三元運算符的方式
import 'package:flutter/material.dart'; import 'search_bar_demo.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData.light(),//輕量級的皮膚 home: SearchBarDemo() ); } }
import 'package:flutter/material.dart'; import 'asset.dart'; class SearchBarDemo extends StatefulWidget { @override _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()); }, ) ], ), ); } } 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),//關閉context上下文 ); } @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 build) { final suggestionList=query.isEmpty ? recentSuggest :searchList.where((input)=> input.startsWith(query)).toList(); //這裏發返回動態列表 return ListView.builder( itemCount: suggestionList.length, itemBuilder: (contex,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=[ "jiejie-大長腿", "jiejie-水蛇腰", "gege-帥氣歐巴", "gege-小鮮肉", ]; //默認的數組 const recentSuggest=[ "推薦-1", "推薦-2" ];