flutter实现搜索框
生活随笔
收集整理的這篇文章主要介紹了
flutter实现搜索框
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 提示
- 實現效果
- 實現代碼
- 測試代碼
提示
已將代碼上傳至gitee,后續會繼續更新學習封裝的一些組件:
flutter練習
實現效果
實現代碼
import 'package:flutter/material.dart';/// @author longzipeng /// @創建時間:2022/3/29 /// 查詢組件 class SearchWidget extends StatefulWidget {final double? height; // 高度final double? width; // 寬度final String? hintText; // 輸入提示final ValueChanged<String>? onEditingComplete; // 編輯完成的事件回調const SearchWidget({Key? key,this.height,this.width,this.hintText,this.onEditingComplete}): super(key: key);@overrideState<SearchWidget> createState() => _SearchWidgetState(); }class _SearchWidgetState extends State<SearchWidget> {var controller = TextEditingController();@overridevoid initState() {super.initState();}/// 清除查詢關鍵詞clearKeywords() {controller.text = "";}@overrideWidget build(BuildContext context) {return LayoutBuilder(builder: (context, constrains) {var width = widget.width ?? constrains.maxWidth / 2; // 父級寬度var height = widget.width ?? widget.height ?? 30;return Container(width: width,height: height,decoration: BoxDecoration(border: Border.all(color: Theme.of(context).primaryColor),borderRadius: BorderRadius.circular(height)),child: TextField(controller: controller,decoration: InputDecoration(hintText: widget.hintText ?? "請輸入搜索詞",hintStyle: TextStyle(color: Colors.grey, fontSize: 14),contentPadding: EdgeInsets.only(bottom: height / 3),border: InputBorder.none,icon: Padding(padding: const EdgeInsets.only(left: 10, top: 5),child: Icon(Icons.search,size: 18,color: Theme.of(context).primaryColor,)),suffixIcon: IconButton(icon: const Icon(Icons.close,size: 17,),onPressed: clearKeywords,splashColor: Theme.of(context).primaryColor,)),onEditingComplete: () {widget.onEditingComplete?.call(controller.text);}),);});} }測試代碼
import 'package:csdn_flutter_demo/pages/common/common_appbar.dart'; import 'package:csdn_flutter_demo/widgets/search_widget.dart'; import 'package:flutter/material.dart';/// @author longzipeng /// @創建時間:2022/3/30 /// 下拉選擇demo class SearchDemoPage extends StatefulWidget {const SearchDemoPage({Key? key}) : super(key: key);@overrideState<SearchDemoPage> createState() => _SearchDemoPageState(); }class _SearchDemoPageState extends State<SearchDemoPage> {/// 查詢數據search(value) {print("搜索的值為:$value");}@overrideWidget build(BuildContext context) {return Scaffold(appBar: CommonAppbar(title: "搜索框演示",),body: Center(child: SearchWidget(onEditingComplete: search,),));} }總結
以上是生活随笔為你收集整理的flutter实现搜索框的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 题解 - HDU 6638 Snowy
- 下一篇: IDEA编译代码报错,找不到符号:找不到