Flutter-19-搜索条

2019-05-29  本文已影响0人  忆往昔Code

主入口文件

这个还是继承StatelessWidget,然后在home属性中加入SearchBarDemo,这是一个自定义的Widget,主要代码都在这个文件中。

main.dart 文件的代码如下:

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()
);
}
}

asset.dart相当于数据文件,工作中这些数据是后台传递给我们,或者写成配置文件的,这里我们就以List的方式代替了。我们在这个文件中定义了两个List:

整体代码如下 :

const searchList = [
"jiejie-大长腿",
"jiejie-水蛇腰",
"gege1-帅气欧巴",
"gege2-小鲜肉"
];

const recentSuggest = [
"推荐-1",
"推荐-2"
];

AppBar的样式制作:
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: (){
print('开始搜索');
}
),
]
)
);

}
}

全部代码
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))
])),
));
}

}

上一篇下一篇

猜你喜欢

热点阅读