In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how to use Basics Widget, the basic component of Flutter, which is very detailed and has certain reference value. Friends who are interested must finish reading it.
1. Overview
Basics Widget is not a special Widget category of Flutter, but Flutter officially selects some commonly used Widget for development, hoping that we can master some of the most basic development capabilities.
These include:
Text Text
Button Button
Picture Image
Check boxes, check boxes
Input box, form
Indicator
Container
...
two。 Common components 2.1 Text
Text is used to display simple style text, and then you can populate some properties of the text display style, as shown in the following example:
Text ("Hello World", textAlign: TextAlign.left, maxLines: 1, overflow: TextOverflow.ellipsis, textScaleFactor: 1.5)
TextAlign
Text alignment
MaxLines 、 overflow
MaxLines specifies the maximum number of lines of text to display.
When the content of the text exceeds the maximum number of lines, overflow specifies the phase method. For example, ellipsis uses the excess text with "…" Express
TextScaleFactor
The zoom factor that represents the text relative to the current font size. For fontSize, which sets the style property of the text style, it is a shortcut to adjust the font size. The default value of this property can be obtained through MediaQueryData.textScaleFactor. If there is no MediaQuery, the default value will be 1.0.
2.1.1 TextStyle
TextStyle is used to specify text styles, such as color, font, weight, background, and so on, as follows:
@ override Widget build (BuildContext context) {return MaterialApp (title: "Flutter", home: Scaffold (appBar: AppBar (title: const Text ("Basics Widget"),), body: Text ("Hello World", style: TextStyle (color: Colors.blue) FontSize: 19.0, height: 2, fontFamily: "Courier", background: Paint (). Color = Colors.yellow, decoration: TextDecoration.underline, decorationStyle: TextDecorationStyle.dashed),) }
The effect is as shown in the figure:
Some attributes:
Height
Row height, which is not an absolute value, because the specific row height is height*fontSize, so is the row width.
FontFamily
Since different platforms support different font sets by default, be sure to test them on different platforms before manually specifying fonts.
FontSize
Both the change attribute and Text's textScaleFactor are used to control font size, but there are two differences
①: fontSize can specify the font size precisely, while textScaleFactor can only scale.
②: textScaleFactor is mainly used to globally adjust Flutter fonts when the system font size is changed, while fontSzie is usually used for a single text, and the font size does not change with the system font size
2.1.2 TextSpan
If we need to display different parts of the Text content in different styles, we can use TextSpan, which represents a "fragment" of the text, and look at the definition of TextSpan:
Const TextSpan ({this.text, this.children, TextStyle? Style, this.recognizer, MouseCursor? MouseCursor, this.onEnter, this.onExit, this.semanticsLabel, this.locale, this.spellOut,})
Where style and text represent style and text content, and children is List? Type, that is, TextSpan can contain other Span
Reconizer is used to indicate that the text fragment is used for gesture recognition processing. Let's look at an effect image and then implement it with TextSpan:
Body: const Text.rich (children: [TextSpan (text: "Home:"), TextSpan (text: "https://flutterchina.club", style: TextStyle (color: Colors.blue), recognizer: _ recognizer),])
The code here implements a basic text and a link fragment in TextSpan
The Text.rich method adds TextSpan to Text because Text is actually a wrapper for RichText, and RichText can display a variety of widget
_ reconizer is the processor that clicks the link
2.1.3 DefaultTextStyle
In the Widget tree, the text style can be inherited by default, so if you set a default text style at a node of the Widget tree, all text in the node's subtree will use this style by default, and DefaultTextStyle is used to set the default text style, see the following example:
DefaultTextStyle (/ / 1. Set the text default style style: TextStyle (color:Colors.red, fontSize: 20.0,), textAlign: TextAlign.start, child: Column (crossAxisAlignment: CrossAxisAlignment.start, children: [Text ("hello world"), Text ("I am Jack"), Text ("I am Jack", style: TextStyle (inherit: false, / / 2. Do not inherit the default style color: Colors.grey),),],),)
The code here first sets a default style with a font size of 20 and a color of red, and then sets DefaultTextStyle to the subtree, so that all descendants of Column Text inherit this style by default, unless Text sets inherit: false, as shown below:
2.1.4 use fonts
Custom fonts or other third-party fonts can be used in Flutter. The configuration is not introduced here. For more information, please see the official document: fonts.
2.2 Button
The Material component library provides a variety of buttons, all of which directly or indirectly customize the wrapper of RawMaterialButton, so most of the properties are the same. In addition, the buttons in the Marterial library have the following in common:
There are water ripples when pressed.
The animation uses the onPressed attribute to set the callback, which is executed when the button is pressed. If the callback is not provided, the button will be disabled and will not respond to the user's click.
2.2.1 ElevatedButton
That is, the button with shadow has a shadow and gray background by default, and the shadow becomes larger when pressed, as shown below:
The code is as follows:
Child: ElevatedButton (child: const Text ("i am ElevatedButton"), onPressed: () {},), 2.2.2 TextButton
The text button will have a background color when pressed, as shown in the following image:
2.2.3 OutlinedButton
By default, there is a border with no shadow and the background is transparent. when pressed, the border color brightens and both background and shadow appear, as shown in the following illustration:
2.2.4 IconButton
The Icon that can be clicked does not contain text, and the background appears after clicking, as shown below:
The code is set to:
IconButton (icon: Icon (Icons.eleven_mp), onPressed: () {},), 2.2.5 buttons with icons
ElevatedButton, TextButton, and OutlinedButton all have a constructor of icon () that can be substituted for an image, such as setting:
ElevatedButton.icon (icon: const Icon (Icons.send), label: const Text ("send"), onPressed: () {},)
The effect is (there is a coding problem here, which can be ignored):
2.3Images and Icon2.3.1 pictures
Layouts can be loaded and displayed through the Image component, and the data source for Image can be
Asset
File
Memory
The network
2.3.1.1 ImageProvider
ImageProvider is an abstract class, which mainly defines the image acquisition interface load (). To obtain pictures from different data sources, you need to implement different ImageProvider. For example, AssetImage implements loading pictures from Asset, and NetworkImage implements loading pictures from the network.
2.3.1.2 Image Widget
The Image component has a required image parameter when building, which corresponds to an ImageProvier. The following shows how to load images from asset and the network, respectively.
1. Load pictures from asset
Create an images directory under the root of the project, and copy the pictures to that directory.
Next, in the flutter section of the pubspec.yaml file, write (note indentation):
Flutter:.. Assets:-assets/images/bobo.jpg
Finally, use in the code:
Image (image: AssetImage ("images/bobo.jpg"), width: 100.0,)
You can show the picture.
(however, I have encountered a problem here. Running the Flutter application on my phone can display the picture normally, but using the Chrome simulator will report an error. I don't know what caused it.
two。 Load pictures from the network URL
Use the code directly:
Image (image: NetworkImage ("https://www.wahaotu.com/uploads/allimg/201904/1554901831804910.jpg"), width: 100.0,)
The picture can be displayed normally.
(however, there is the same problem as above, but using the official url can display the picture normally.
2.3.1.3 Image parameters
We can take a look at the parameters of Image, through which you can control the appearance, size, blending effect of the image, and so on.
Const Image ({Key? Key, required this.image, this.frameBuilder, this.loadingBuilder, this.errorBuilder, this.semanticLabel, this.excludeFromSemantics = false, this.width, this.height, this.color, this.opacity, this.colorBlendMode, this.fit, this.alignment = Alignment.center, this.repeat = ImageRepeat.noRepeat, this.centerSlice, this.matchTextDirection = false, this.gaplessPlayback = false, this.isAntiAlias = false This.filterQuality = FilterQuality.low,})
Width 、 height
Set the width and height of the picture. When you do not specify the width and height, the original size will be displayed as much as possible according to the limitations of the current parent container. If only one of them is set, the other property will be scaled by default.
Fit
This property is used to specify the adaptation mode of the picture when the display space of the picture is different from the size of the picture itself. The adaptation pattern is defined in BoxFit, which is an enumerated type with these values:
① fill: stretch to fill the display space, and the picture will be
② cover: the image will be centered to fill the display space after being enlarged according to the aspect ratio of the picture. The image will not be deformed, and the part beyond the display will be clipped.
③ contain: the picture adapts to the rules by default, and the picture will be scaled to adapt to the current display space without changing the aspect ratio of the picture itself.
④ fitWidth: the width of the picture will be scaled to the width of the display space, the height will be scaled proportionally, it will be centered, and the picture will not be deformed.
⑤ fitHeight: the opposite of the above
⑥ none: the picture has no adaptation strategy and will be displayed in the display space.
Color and colorBlendMode: when drawing a picture, you can mix the color of each pixel. Color specifies the mixed color, while colorBlendMode specifies the mixed mode. Because it is rarely used, there is no example here.
Repeat: when the size of the image itself is smaller than the display space, specify the repetition rule of the picture, and it will not be displayed here.
2.3.2 Icon
There are svg vector graphs in Android, and so do in Flutter, which is Icon, which has the following advantages:
Small in size
Because it is a vector diagram, stretching will not affect the clarity.
Can be mixed with TextSpan and text
Can be referenced to a text style
Flutter implements a set of Icon by default, which can be seen in the configuration file of pubspec.yaml:
Flutter: uses-material-design: true
Take a look at the official sample code:
String icons = ""; / / accessible: 0xe03eicons + = "\ uE03e"; / / error: 0xe237icons + = "\ uE237"; / / fingerprint: 0xe287icons + = "\ uE287"; Text (icons, style: TextStyle (fontFamily: "MaterialIcons", fontSize: 24.0, color: Colors.green,))
The effect is:
In order not to allow developers to code, Flutter encapsulates IconData and Icon to display font images. The above example can also be implemented in the following ways:
Row (mainAxisAlignment: MainAxisAlignment.center, children: [Icon (Icons.accessible,color: Colors.green), Icon (Icons.error,color: Colors.green), Icon (Icons.fingerprint,color: Colors.green),],)
We can also use custom font icons. Instead of going into detail here, we can take a look at the official example: Icon custom font icons.
2.4 Radio switches and check boxes
Flutter provides Material-style switch Switch and check box Checkbox, which are inherited from StatfulWidget, but they do not save the selected state, which is managed by the parent component. When Switch or Checkbox is clicked, the onChanged callback will be triggered. We can deal with the selected state change logic in this callback. Here is an official example:
Class SwitchAndCheckBoxTestRoute extends StatefulWidget {@ override _ SwitchAndCheckBoxTestRouteState createState () = > _ SwitchAndCheckBoxTestRouteState ();} class _ SwitchAndCheckBoxTestRouteState extends State {bool _ switchSelected=true; / / maintain radio switch state bool _ checkboxSelected=true / / maintenance checkbox status @ override Widget build (BuildContext context) {return Column (children: [Switch (value: _ switchSelected,// current status onChanged: (value) {/ / rebuild page setState (() {_ switchSelected=value;})) },), Checkbox (value: _ checkboxSelected, activeColor: Colors.red, / / selected color onChanged: (value) {setState () {_ checkboxSelected=value! ;});},)],);}}
The selected states of Switch and Checkbox need to be maintained in the code, so Widget inherits from StatefulWidget. In its build method, the state is Switch and Checkbox respectively, and two bool values are used to maintain the selected state respectively. When the button is clicked, the selected state of the onChanged callback will be called back. In this case, we need to call the setState () method to trigger the Flutter redrawing.
Why is it designed like this? my understanding is:
Throwing the status of switches and check boxes to the parent component can be more flexible, such as making some network requests, that is, asynchronous operations when checked.
Generally speaking, whether these item are selected or not is associated with user data, and user data cannot be their private state, so it is better to manage them together.
2.4.1 Properties
Their properties are relatively simple, and the common ones are:
ActiveColor: sets the color of the active stat
Tristate: three states are available only for Checbox. Generally speaking, only "true" and "false" are selected, indicating whether they are selected or unselected. If tristate is set, a "null" status will be added.
In addition, Checkbox cannot set width and height, and its size is custom, while Switch can only set width.
2.5 input boxes and forms
The Flutter Material component provides input TextField and form Form
2.5.1 input box TextField2.5.1.1 property
Take a look at the properties provided by TextField:
Const TextField ({... This.controller, this.focusNode, this.decoration = const InputDecoration (), TextInputType? KeyboardType, this.textInputAction, this.textCapitalization = TextCapitalization.none, this.style, this.strutStyle, this.textAlign = TextAlign.start, this.textAlignVertical, this.textDirection, this.readOnly = false, ToolbarOptions? ToolbarOptions, this.showCursor, this.autofocus = false, this.obscuringCharacter ='', this.obscureText = false, this.autocorrect = true, SmartDashesType? SmartDashesType, SmartQuotesType? SmartQuotesType, this.enableSuggestions = true, this.maxLines = 1, this.minLines, this.expands = false, this.maxLength, this.maxLengthEnforcement, this.onChanged, this.onEditingComplete, this.onSubmitted, this.onAppPrivateCommand, this.inputFormatters, this.enabled, this.cursorWidth = 2.0, this.cursorHeight, this.cursorRadius, this.cursorColor, this.selectionHeightStyle = ui.BoxHeightStyle.tight, this.selectionWidthStyle = ui.BoxWidthStyle.tight This.keyboardAppearance, this.scrollPadding = const EdgeInsets.all, this.dragStartBehavior = DragStartBehavior.start, this.enableInteractiveSelection = true, this.selectionControls, this.onTap, this.mouseCursor, this.buildCounter, this.scrollController, this.scrollPhysics, this.autofillHints, this.restorationId, this.enableIMEPersonalizedLearning = true,})
There are many properties, so list a few key explanations:
Controller
The controller of the edit box, through which you can set / get the contents of the edit box, select the editing content, and listen for editing text change events. In most cases, we need to display and provide a controller to interact with the text box. If set, one will be created inside the TextField.
FocusNode
Used to control whether TextField occupies the input focus of the current keyboard
InputDecoration
Used to control the appearance of the TextField, such as prompt text, background color, border, and so on.
KeyboardType
Used to set the default keyboard input type of the input box, such as text, phone, email, etc.
TextInputAction
The keyboard action button icon, which is the icon setting in the lower right corner.
Style
The style of the text (being edited)
TextAlign
Edit the horizontal alignment of the text in the input box
Autofocus
Whether to get focus automatically
ObscureText
Whether to hide the text being edited, such as entering a password, the text content will be replaced by "".
MaxLines
Maximum number of rows
MaxLenth and maxLengthEnforcement
MaxLenth represents the maximum length of the text in the input box. After setting, the lower right corner of the input box will display the count of entered text.
MaxLengthEnforcement decides what to do when the length of input text exceeds maxLength, such as truncation
ToolbarOptions
For menus that appear on time, you can choose copy, cut, paste, and selectAll.
OnChange
Callback for changes in the contents of the input box. Of course, controller can also monitor
OnEditingComplete 、 onSubmitted
The function is the same, it is triggered when the input is completed, for example, the completion key of the keyboard is clicked and the search key is different because the two callback signatures are different.
InputFormatters
Specifies the input format, which will be verified according to the specified format when the user's input changes
Enable
If false, the input box is disabled
CursorWidth 、 cursorRadius 、 cursorColor
Represents the cursor width, fillet and color of the custom input box, respectively
A simple setting code is as follows:
Column (children: const [TextField (autofocus: true, decoration: InputDecoration (labelText: "user name", hintText: "Please enter user name or password", prefixIcon: Icon (Icons.person)), TextField (decoration: InputDecoration (labelText: "password") HintText: "Please enter password", prefixIcon: Icon (Icons.lock)), obscureText: true,)])
2.5.1.2 get input via controller
We can get the content through onChange. Of course, you can also use controller to get
The steps are:
Define a controller:final TextEditingController _ tfController = TextEditingController (); then pass the controllerTextField (controller: _ tfController,...) in the TextFiled.
Finally, you can get the contents of the input box through: print (_ tfController.text)
2.5.1.3 listening for changes in text content through controller
You can listen to text through onChange, and controller can listen to text by setting a listener, as follows:
@ override void initState () {super.initState (); _ tfController.addListener (() {print (_ tfController.text);});}
Controller has more functions, in addition to listening to text, you can also set default values, select text, and so on.
2.5.1.4 Control focus
You can use FocusNode and FocusScopeNode to control focus. By default, it is managed by FocusScope, within which you can move the focus between input boxes and set the default focus through FocusScopeNode.
We can get the default FocusScopeNode in the current Widget tree with the following code:
FocusScopeNode = FocusScope.of (context)
After you get the handle, you can use the following code to get the focus:
FocusScopeNode.requestFocus (focusNode)
Where focucsNode is the FocusNode created for TextField, and this operation allows the TextField to get focus. Call focusNode.unfocus () to remove focus.
2.5.1.5 listen for focus state change events
FocusNode allows you to listen for events with a change of focus:
FocusNode.addListener (() {print (focusNode.hasFocus);})
True to gain focus, false to lose focus
2.5.2 form
The form Form groups and unifies the input boxes. Just as RadioGroup, the native component of Android, is to RadioButton, Form can manage content validation, input box resets, and so on.
Form inherits from StatefulWidget, and its state management is in FormState. Take a look at the definition of From:
Class Form extends StatefulWidget {const Form ({Key? Key, required this.child, @ Deprecated ('Use autovalidateMode parameter which provides more specific' 'behavior related to auto validation.' 'This feature was deprecated after v1.19.0.percent,) this.autovalidate = false, this.onWillPop, this.onChanged, AutovalidateMode? AutovalidateMode,}).
Autovalidate
Whether to automatically verify the input content. When it is true, the validity of each FormField content will be checked when it changes, and the error message will be displayed directly. Otherwise, you will need to verify manually by calling FormState.validate ().
V1.19 has been abandoned and replaced with AutovalidateMode
AutovalidateMode
The automatic check mode, which is the replacement above, has three enumerated values:
① disable: no verification is made when the content of FormField changes
② always: verify validity even if the user does not have user interaction
③ onUserInteraction: verifies validity only when users interact with each other
OnWillPop
Determines whether the route where the Form is located can be returned directly. The callback returns a Future object, and if the final result of Future is false, the current route will not return, and if true, it will return to the previous route.
This property is usually used to intercept the return button
OnChanged
This method is called when any one of the FormField contents of Form changes
2.5.2.1 FormField
The descendant element of Form is the FormField type, and FormField is an abstract class that defines several attributes. The operation is done internally through them in FormState. The FormField part is defined as follows:
Const FormField ({Key? Key, required this.builder, this.onSaved, this.validator, this.initialValue, @ Deprecated ('Use autovalidateMode parameter which provides more specific' 'behavior related to auto validation.' 'This feature was deprecated after v1.19.0.33,) this.autovalidate = false, this.enabled = true, AutovalidateMode? AutovalidateMode, this.restorationId,})
OnSaved
Callback when saving
Validator
Callback to verify legitimacy
InitValue
Initial value
For ease of use, Flutter provides a TextFormFild component that inherits from the FormField class and wraps TextFileld, which can be used directly as the FormField of Form, which is equivalent to managing TextField with Form
2.5.2.2 FormState
The status class of the Form form is FormState, which can be obtained through Form.of or GlobalKey, which can be used to unify the operation of FormField, the descendants of Form.
There are three common methods for FormState:
FormState.validate (): after calling this method, the Form descendant FormField.validate () callback will be called. If a check fails, false will be returned, so that all Widget whose verification fails will give an error prompt.
FormState.save (): after calling this method, the descendant's FormFild.save () callback is called to save the form content.
FormState.reset (): will empty the content of the descendant FormField
2.5.2.3 exampl
We do a user login program, and then click to log in before we need to do the input check:
The user name cannot be empty. If it is empty, it will prompt "user name cannot be empty".
The password cannot be less than 6 digits. If it is less than 6 digits, it prompts "the password cannot be less than 6 digits".
The code is as follows:
Import 'package:flutter/material.dart';class FormTestRoute extends StatefulWidget {const FormTestRoute ({Key? Key}): super (key: key); @ override State createState () = > _ FormTestRouteState ();} class _ FormTestRouteState extends State {final TextEditingController _ usernameController = TextEditingController (); final TextEditingController _ passwordController = TextEditingController (); final GlobalKey _ formKey = GlobalKey () @ override Widget build (BuildContext context) {return Scaffold (appBar: AppBar (title: const Text ('Form demo'),), body: Form (key: _ formKey, autovalidateMode: AutovalidateMode.onUserInteraction, child: Column (children: [TextFormField (autofocus: true) Controller: _ usernameController, decoration: const InputDecoration (labelText: "username", hintText: "username or email", icon: Icon (Icons.person)) Validator: (username) {return usernameroom.trim () .isNotEmpty? Null: "username cannot empty" },), TextFormField (controller: _ passwordController, decoration: const InputDecoration (labelText: "password", hintText: "please input your password", icon: Icon (Icons.lock)) ObscureText: true, validator: (pwd) {return pwdflowers. Trim (). Length > = 6? Null: "password digit cannot less than 6!" }, / / login button Padding (padding: const EdgeInsets.only (top: 28.0) Child: Row (children: [Expanded (child: ElevatedButton (onPressed:) {if ((_ formKey.currentState as FormState). Validate ()) {print ("Loing success")) }, child: const Padding (padding: EdgeInsets.all, child: Text ("Login"),))] ),) }}
The effect is shown in the following figure:
The above is all the contents of the article "how to use Basics Widget, the basic components of Flutter". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.