Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement self-defined search box AppBar by Flutter

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "Flutter how to achieve a custom search box AppBar", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Flutter how to achieve a custom search box AppBar" bar!

Introduction

In development, the design of a search style for the page header is very common, and in order to be used like the system AppBar, this article records the customization of a general search box AppBar record in Flutter.

Function points: search box, return key, clear search content function, keyboard processing.

Effect picture

Implementation steps

First of all, let's take a look at the source code of AppBar and implement the PreferredSizeWidget class. We can know that this class mainly controls the height of AppBar. The parameter type of AppBar in Scaffold scaffolding is the PreferredSizeWidget type.

Class AppBar extends StatefulWidget implements PreferredSizeWidget {... preferredSize = _ PreferredAppBarSize (toolbarHeight, bottom?.preferredSize.height),. / / {@ template flutter.material.appbar.toolbarHeight} / / Defines the height of the toolbar component of an [AppBar]. / By default, the value of `toolbarHeight` is [kToolbarHeight]. / / {@ endtemplate} final double? ToolbarHeight;.../// The height of the toolbar component of the [AppBar] .const double kToolbarHeight = 56.0;} abstract class PreferredSizeWidget implements Widget {/ / set the desired size / / set height without constraints: Size.fromHeight (myAppBarHeight) Size get preferredSize;}

To facilitate extension and use in Scaffold, we need to create an AppBarSearch class that inherits the stateful StatefulWidget class and implements the PreferredSizeWidget class, implements the preferredSize method, and sets the height.

Class AppBarSearch extends StatefulWidget implements PreferredSizeWidget {@ overrideSize get preferredSize = > Size.fromHeight (height);}

Because Scaffold adapts the status bar to AppBar, see the following source code for the core:

/ / get the status bar height MediaQuery.of (context) .padding.top

Here we go directly back to AppBar and modify it. (of course, we don't have to return the height of the AppBar status bar here.)

Idea: AppBar title field custom input box, mainly through the text box monitoring to clear search content and display the clear button function, through the input box whether there is focus monitoring to refresh the layout, through the definition of callback function to monitor the search content.

/ / input box control _ controller = widget.controller? TextEditingController (); / / focus control _ focusNode = widget.focusNode? FocusNode (); / / focus acquisition loses listening _ focusNode?.addListener (() = > setState (() {})); / / text input monitoring _ controller?.addListener (() = > setState (() {})

Keyboard search monitor:

You only need to set these two properties of TextField.

TextInputAction: TextInputAction.search,onSubmitted: widget.onSearch, / / input box to complete trigger

Keyboard eject and fold processing:

In iOS, we need to deal with the keyboard ourselves. The function we need is to click outside the search box to lose focus and close the keyboard. Here I use a plug-in to deal with the keyboard: flutter_keyboard_visibility: ^ 5.1.0. When we need to deal with the focus events page root layout, we can use the KeyboardDismissOnTap external package. This plug-in can also actively control the pop-up and folding of the keyboard. Interested friends can learn about it.

Return KeyboardDismissOnTap (child: Material (); complete source code / search for AppBarclass AppBarSearch extends StatefulWidget implements PreferredSizeWidget {AppBarSearch ({Key? Key, this.borderRadius = 10, this.autoFocus = false, this.focusNode, this.controller, this.height = 40, this.value, this.leading, this.backgroundColor, this.suffix, this.actions = const [], this.hintText, this.onTap, this.onClear, this.onCancel, this.onChanged, this.onSearch, this.onRightTap,}): super (key: key); final double? BorderRadius; final bool? AutoFocus; final FocusNode? FocusNode; final TextEditingController? Controller; / / the height of the input box defaults to 40 final double height; / / default final String? Value; / / the front component final Widget? Leading; / / background color final Color? BackgroundColor; / / search box internal suffix component final Widget? Suffix; / / search box right component final List actions; / / input box prompt text final String? Click on the hintText; / / input box to call back final VoidCallback? OnTap; / / clear the contents of the input box and call back final VoidCallback? OnClear; / / clear the contents of the input box and cancel entering final VoidCallback? OnCancel; / / change the contents of the input box final ValueChanged? OnChanged; / / Click the keyboard to search for final ValueChanged? OnSearch; / / Click widget final VoidCallback on the right? OnRightTap; @ override _ AppBarSearchState createState () = > _ AppBarSearchState (); @ override Size get preferredSize = > Size.fromHeight (height);} class _ AppBarSearchState extends State {TextEditingController? _ controller; FocusNode? _ focusNode; bool get isFocus = > _ focusNode?.hasFocus? False; / / do you want to get the focus bool get isTextEmpty = > _ controller?.text.isEmpty? Is the false; / / input box empty bool get isActionEmpty = > widget.actions.isEmpty; / / is the layout on the right empty bool isShowCancel = false; @ override void initState () {_ controller = widget.controller?? TextEditingController (); _ focusNode = widget.focusNode? FocusNode (); if (widget.value! = null) _ controller?.text = widget.value? ""; / / focus acquisition loss listening _ focusNode?.addListener (() = > setState (() {})); / / text input listening _ controller?.addListener (() {setState (() {});}); super.initState () } / / clear the contents of input box void _ onClearInput () {setState (() {_ controller?.clear ();}); widget.onClear?.call ();} / cancel input box editing to lose focus void _ onCancelInput () {setState (() {_ controller?.clear (); _ focusNode?.unfocus (); / / lose focus}) / / execute onCancel widget.onCancel?.call ();} Widget _ suffix () {if (! isTextEmpty) {return InkWell (onTap: _ onClearInput, child: SizedBox (width: widget.height, height: widget.height, child: Icon (Icons.cancel, size: 22, color: Color (0xFF999999)),);} return widget.suffix?? SizedBox ();} List _ actions () {List list = [] If (isFocus | |! isTextEmpty) {list.add (InkWell (onTap: widget.onRightTap? _ onCancelInput, child: Container (constraints: BoxConstraints (minWidth: 48.w), alignment: Alignment.center, child: MyText ('search', fontColor: MyColors.color_666666, fontSize: 14.sp,),) )) } else if (! isActionEmpty) {list.addAll (widget.actions);} return list;} @ override Widget build (BuildContext context) {return AppBar (backgroundColor: widget.backgroundColor, / / Shadow z-axis elevation: 0, / / interval between title and other controls titleSpacing: 0, leadingWidth: 40.w, leading: widget.leading?? InkWell (child: Icon (Icons.arrow_back_ios_outlined, color: MyColors.color_666666, size: 16.w,), onTap: () {Routes.finish (context) },), title: Container (margin: EdgeInsetsDirectional.only (end: 10.w), height: widget.height, decoration: BoxDecoration (color: Color (0xFFF2F2F2), borderRadius: BorderRadius.circular (widget.borderRadius? 0),) Child: Container (child: Row (children: [SizedBox (width: widget.height, height: widget.height, child: Icon (Icons.search, size: 20.w, color: Color (0xFF999999)),) Expanded (/ / weight flex: 1, child: TextField (autofocus: widget.autoFocus?? False, / / whether to automatically obtain focus focusNode: _ focusNode, / / focus control controller: _ controller / / interaction controller with input box / / decorate decoration: InputDecoration (isDense: true, border: InputBorder.none, hintText: widget.hintText?? 'Please enter keywords', hintStyle: TextStyle (fontSize: 14.sp, color: MyColors.color_666666), style: TextStyle (fontSize: 14.sp, color: MyColors.color_333333,) / / the icon in the lower right corner of the keyboard action textInputAction: TextInputAction.search, onTap: widget.onTap, / / input box content change callback onChanged: widget.onChanged, onSubmitted: widget.onSearch, / / input box complete trigger) ), _ suffix (),],),), actions: _ actions (),) } @ override void dispose () {_ controller?.dispose (); _ focusNode?.dispose (); super.dispose ();}} Thank you for your reading. The above is the content of "how Flutter implements a custom search box AppBar". After the study of this article, I believe you have a deeper understanding of how Flutter implements a custom search box AppBar, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report