Flutter搜索功能插件searchformapi的使用
Flutter搜索功能插件searchformapi的使用
这个包用于从API或其他地方获取数据后进行搜索。
你只需要创建一个模态JSON映射。
创建模态
你可以使用以下工具生成模态: https://app.quicktype.io/
示例代码
以下是完整的示例代码:
import 'package:example/searchfield.dart';
import 'package:flutter/material.dart';
import 'data_modal.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// 这个小部件是你的应用的根。
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: '搜索来自API的数据',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String name = "";
List<dynamic> zoneData = [];
List<dynamic> newZoneData = [];
List<Modal> zoneListStatusMap = [];
bool sectorBool = true;
bool addressBool = true;
TextEditingController selectSector = TextEditingController();
[@override](/user/override)
void initState() {
getDataFromAPI();
super.initState();
}
void getDataFromAPI() {
var data = [
{
"id": "78",
"name": "01",
},
{
"id": "425",
"name": "1",
},
{
"id": "453",
"name": "1",
},
{
"id": "45",
"name": "10",
},
{
"id": "87",
"name": "10",
},
{
"id": "85",
"name": "10-New",
},
{
"id": "786",
"name": "11",
},
{
"id": "465",
"name": "11",
},
{
"id": "657",
"name": "11-New",
},
{
"id": "5",
"name": "12",
},
{
"id": "57",
"name": "12",
},
{
"id": "8",
"name": "12-New",
},
{
"id": "49",
"name": "13",
},
{
"id": "47",
"name": "13",
},
{
"id": "7890",
"name": "13-New",
},
{
"id": "568",
"name": "14",
},
{
"id": "542",
"name": "14",
},
{
"id": "853",
"name": "14-New",
},
{
"id": "964",
"name": "3",
},
{
"id": "7805",
"name": "3",
},
];
setState(() {
zoneData = data;
newZoneData = data;
});
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
void _runZone(String enteredKeyword) {
List<dynamic> results = [];
if (enteredKeyword.isEmpty) {
results = zoneData;
} else {
results = zoneData
.where((user) => user["name"].toLowerCase().contains(enteredKeyword.toLowerCase()))
.toList();
}
setState(() {
newZoneData = results;
zoneListStatusMap = (newZoneData).map<Modal>((de) => Modal.fromMap(de)).toList();
});
}
[@override](/user/override)
Widget build(BuildContext context) {
if (newZoneData.isNotEmpty) {
zoneListStatusMap = (newZoneData).map<Modal>((de) => Modal.fromMap(de)).toList();
}
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Column(
children: <Widget>[
const SizedBox(
height: 45,
),
Focus(
onFocusChange: (cal) {
var contain = zoneData
.where((element) => element['name'] == selectSector.text);
if (contain.isEmpty) {
setState(() {
selectSector.clear();
});
}
},
child: SearchField(
suggestions: zoneListStatusMap
.map((Modal map) =>
SearchFieldListItem(map.name!, item: map))
.toList(),
hint: "选择区域",
suggestionState: Suggestion.hidden,
onChange: (val) {
_runZone(val);
},
cursorColor: sectorBool ? Colors.black54 : Colors.red,
controller: selectSector,
suggestionDirection: SuggestionDirection.down,
onSuggestionTap: (SearchFieldListItem<Modal> x) {
setState(() {
FocusManager.instance.primaryFocus?.unfocus();
setState(() {
if(x.item?.name==null){
name = x.item?.name??"";
}
});
});
},
),
),
const Text(
'你已经按下了按钮这么多次:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
Text(
name,
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: '增加',
child: const Icon(Icons.add),
),
);
}
}
更多关于Flutter搜索功能插件searchformapi的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter搜索功能插件searchformapi的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中实现搜索功能时,searchfield
是一个常用的插件,它提供了一个可定制的搜索输入字段。虽然 searchformapi
不是一个官方的Flutter插件,但你可以使用 searchfield
插件来实现类似的功能。以下是如何使用 searchfield
插件来实现一个基本的搜索功能的示例。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 searchfield
插件的依赖:
dependencies:
flutter:
sdk: flutter
searchfield: ^1.0.0 # 使用最新版本
然后运行 flutter pub get
来安装依赖。
2. 使用 SearchField
下面是一个简单的示例,展示了如何使用 SearchField
组件:
import 'package:flutter/material.dart';
import 'package:searchfield/searchfield.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SearchField Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SearchExample(),
);
}
}
class SearchExample extends StatefulWidget {
@override
_SearchExampleState createState() => _SearchExampleState();
}
class _SearchExampleState extends State<SearchExample> {
final List<String> _suggestions = [
'Apple',
'Banana',
'Orange',
'Mango',
'Pineapple',
'Strawberry',
'Grape',
'Watermelon',
'Kiwi',
'Peach',
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SearchField Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: SearchField(
suggestions: _suggestions,
suggestionState: SuggestionState.enabled,
textInputAction: TextInputAction.search,
onSubmit: (value) {
// Perform search operation here
print('Search for: $value');
},
onSuggestionTap: (value) {
// Handle suggestion tap here
print('Selected: $value');
},
),
),
);
}
}
3. 解释代码
SearchField
: 这是主要的搜索输入组件。你可以通过suggestions
属性提供建议列表。suggestionState
: 控制是否显示建议。SuggestionState.enabled
表示始终显示建议。textInputAction
: 设置键盘上的操作按钮。TextInputAction.search
表示显示搜索按钮。onSubmit
: 当用户提交搜索时调用的回调函数。onSuggestionTap
: 当用户点击建议项时调用的回调函数。
4. 自定义搜索逻辑
你可以根据需要自定义搜索逻辑。例如,你可以在 onSubmit
回调中调用API来获取搜索结果,并更新UI。
5. 处理异步搜索
如果你的搜索涉及到异步操作(例如从API获取数据),你可以在 onSearch
回调中处理异步操作,并根据结果更新建议列表。
SearchField(
suggestions: _suggestions,
suggestionState: SuggestionState.enabled,
textInputAction: TextInputAction.search,
onSubmit: (value) async {
// Perform async search operation here
final results = await searchFromApi(value);
setState(() {
_suggestions = results;
});
},
onSuggestionTap: (value) {
// Handle suggestion tap here
print('Selected: $value');
},
);