1. Text and Style (Text)

Text is used to display simple styled Text, and contains properties that control how the Text is displayed

const Text(
    this.data, {
    Key key,
    this.style,
    this.strutStyle,
    this.textAlign,
    this.textDirection,
    this.locale,
    this.softWrap,
    this.overflow,
    this.textScaleFactor,
    this.maxLines,
    this.semanticsLabel,
    this.textWidthBasis,
    this.textHeightBehavior,
  })
Copy the code

Basic properties

attribute instructions
textAlign Align: left, start, right, end, center, justify
textDirection Textdirection. LTR: left to right, textdirection. RTL: right to left
softWrap Whether to wrap
overflow The clip shows the fade, with the ellipsis in words instead of letters, like Hello worddFSA fdafafsasfs, showing hello…
textScaleFactor The font scaling
maxLines Display to maximum number of rows
semanticsLabel

TextStyle

attribute instructions
inherit The default is true. This property rarely needs to be set to false. The default font is white, 10Pixels
color The font color
fontSize Font size, default 14
fontWeight Font size: FontWeight normal (default), FontWeight bold (bold)
fontStyle Fonts: Normal and italic
fontFamily Set the font, notice the difference with fontStyle
letterSpacing The spacing between letters is 0 by default. The smaller the spacing between negative numbers, the larger the spacing between positive numbers
wordSpacing The smaller the spacing between negative numbers, the greater the spacing between positive numbers. Note the difference with letterSpacing, such as hello, h, e, L, L, and O are each one letter, and hello is a single word
textBaseline Font baseline
height Will be multiplied by fontSize for the row height
locale Set area, the default system area
foreground Foreground = Paint, color foreground must be null
background Background, Paint
shadows shadow
decoration Text underline: underline, underline, underline
decorationColor Line color
decorationStyle Marking style: dashed line, double line, etc

RichText

Application is dependent on the display of the Text, so Text layout is very important, usually Text component can complete most of the demand, it can show different sizes of Text, font, color, etc., if you want to be in a sentence or a paragraph of Text display different style of the Text, the Text components can meet our requirements, You need to use RichText at this point.

Unlike Text, the Text property of RichText is not of type String, but of type TextSpan, which specifies the style and gesture interaction of the Text fragment

TextSpan({
    this.style,
    this.text,
    this.children,
    this.recognizer,
    this.semanticsLabel,
  })
Copy the code

Text is a String and is used to specify a text fragment, style specifies the style of the text fragment, and recognizer specifies the gesture interaction with the text fragment.

TextSpan is a tree structure, and children is a List of children. Each node represents a text fragment. The style of the ancestor node takes effect on all descendant nodes. When the value specified in the style of the ancestor node conflicts with the style of its own node, the value specified in the style of its own node will overwrite the former

class _MyTextPage extends StatelessWidget { Widget _text = Text( "Hello Flutter", textDirection: LTR, style: TextStyle(color: color.red, fontSize: 40.0, fontWeight: fontweight.bold),); Widget _richText(BuildContext context){ return RichText(text: TextSpan( style: DefaultTextStyle.of(context).style, children:<InlineSpan>[ TextSpan(text: "XXX service Agreement", style: TextSpan(color: RGB (51, 51, 51)) Colors.red), recognizer:TapGestureRecognizer()..onTap = () { } ) ], )); } @override Widget build(BuildContext context) { return Container(child: Column( children: <Widget>[ _text, _richText(context) ] )); }}Copy the code

2. Text Input Component (TextField)

TextField is a Material design-style input box, which has a variety of properties. In addition, the InputDecoration also has a variety of properties, but they are relatively simple

TextField

const TextField({ Key key, This. controller,// Controller this.focusNode,// Focus this.decoration = const InputDecoration(),// Decorate TextInputType KeyboardType,// keyboardType, The input type enclosing textInputAction, / / keyboard button this. TextCapitalization = textCapitalization. None, / / case enclosing style, / / style This.strutstyle, this.textalign = textalign.start,// Align this.textDirection, This. autofocus = false,// autofocus this.obscureText = false,// Whether to hide text, This. Autocorrect = true,// autocorrect this. MaxLines = 1,// Maximum number of lines, This. MinLines,// minLines this. {} = false, this. MaxLength,// Max input number, Have value after the bottom right hand corner there will be a counter this. MaxLengthEnforced = true, enclosing onChanged, / / input change callback enclosing onEditingComplete, / / input is completed, OnSubmitted // If this. Enabled is enabled, enter TextInputAction this.inputFormatters // If this This. cursorWidth = 2.0,// cursorWidth this.cursorRadius,// cursorWidth this.cursorColor,// cursorColor this.keyboardAppearance, This. ScrollPadding = const edgeinsets.all (20.0), this. DragStartBehavior = DragStartBehavior.start, Enclosing enableInteractiveSelection, enclosing onTap, / / click event enclosing buildCounter, enclosing scrollPhysics,})Copy the code

InputDecoration decoration

Const InputDecoration({this.icon,// this. LabelText, const InputDecoration({this.icon,// This. HintText this.labelStyle,// Float the text style this.helperText,// help text this.helperStyle, this.hintText,// input the text prompt this.hintStyle, HintMaxLines, this.errorText,// error: this.errorStyle, this.errorMaxLines, Enclosing hasFloatingPlaceholder = true, / / whether show this. The suspension prompt letter isDense, This. ContentPadding,// Fill this. PrefixIcon,// left inside the icon this.prefix, this.prefixText,// left inside the text this.prefixStyle, Suffix, this.suffixText, this.suffixStyle, Counter,// customize counter this.counterText,// count text this.counterStyle,// count style this.filled,// fill this. FillColor,// fillColor this.errorBorder, this.focusedBorder, this.focusedErrorBorder, this.disabledBorder, this.enabledBorder, This border, / / frame enclosing enabled = true, enclosing semanticCounterText, enclosing alignLabelWithHint,})Copy the code

Get input

There are two ways:

  • onChanged

OnChanged is a callback to input changes and returns a String value that can be remembered as a variable

TextField(onChanged: (text) {print(" input changed "+ text); },),Copy the code
  • Controller: controller initialization:
var controller;
  @override
  void initState() {
    super.initState();
    controller = TextEditingController();
    controller.addListener(() {});
  }
Copy the code

Configuration to the TextField

TextField(controller: controller,),
Copy the code

Access to content

controller.text
Copy the code

Calling controller.text in the event returns the input.

Close the soft keyboard

Often we need to turn off the soft keyboard when submitting in an event

Here we use the focusNode

1. Initialize: FocusNode userFocusNode = FocusNode(); TextField(focusNode: userFocusNode,); 3. Then call userFocusNode.unfocus() where necessary.Copy the code

check

It actually has an inputFormatters property

final List<TextInputFormatter> inputFormatters;
Copy the code

TextInputFormatter source code, there are three subclasses:

  • BlacklistingTextInputFormatter
  • WhitelistingTextInputFormatter
  • LengthLimitingTextInputFormatter

Blacklists, whitelists, and length limits. Let’s take a look at one of them and see how the source code implements verification:

static final BlacklistingTextInputFormatter singleLineFormatter
      = BlacklistingTextInputFormatter(RegExp(r'\n'));
Copy the code

The key word is RegExp, which is just regular expressions we use in general.

In this way, we can also customize the verification rules, such as the verification of mobile phone number:

String validateMobile(String value) { String patttern = r'(^[0-9]*$)'; RegExp regExp = new RegExp(patttern); If (value.length == 0) {return "Phone number is empty "; } else if (! RegExp. HasMatch (value)) {return "Invalid phone number format "; } return null; }Copy the code

The above is just our general verification, it is still recommended to use From to wrap TextFormField for forms

abnormal

  • Soft keyboard pops up after cover
  • Soft keyboard after the high overflow

Solution: Wrap it around a sliding component (ListView, etc.) so that when the soft keyboard pops up, the input box automatically slides up.

3. Button components

Flutter offers more than 10 button-like components, Such as RaisedButton, FlatButton, OutlineButton, DropdownButton, RawMaterialButton, PopupMenuButton, IconButton, BackButton, CloseButton , ButtonBar, ToggleButtons, etc.

Common button components are: RaisedButton, FlatButton, IconButton, OutlineButton, ButtonBar, FloatingActionButton, etc.

  • RaisedButton: RaisedButton, which is actually a Material Design style Button
  • FlatButton: FlatButton
  • OutlineButton: wire frame button
  • IconButton: IconButton
  • ButtonBar: button group
  • FloatingActionButton: Float button

Commonly used attributes

In FLUTTER, the button component has the following common properties:

attribute instructions
onPressed Mandatory argument, the callback triggered when the button is pressed, receives a method, passes NULL to indicate that the button is disabled, and displays the disabled style
textColor Text color
color Text color
disabledColor Color of the button when disabled
disabledTextColor The text color of the button when disabled
splashColor The color of the water ripple when the button is clicked
highlightColor Color of the button after clicking (long pressing) the button
elevation : Shadow range. The greater the value, the greater the shadow range
shape Sets the shape of the button

RaisedButton

RaisedButton is a material style “raised” button.

Widget _RaisedButton = RaisedButton(
    child: Text('RaisedButton'),
    onPressed: (){
    },
  );
Copy the code

FlatButton

FlatButton is a FlatButton that is used in the same way as RaisedButton. The code is as follows:

Widget _FlatButton = FlatButton(
    child: Text('Button'),
    color: Colors.blue,
    onPressed: () {},
  );

Copy the code

OutlineButton

OutlineButton is a border button, used in the same way as RaisedButton, with the following code:

Widget _OutlineButton = OutlineButton(
    borderSide: BorderSide(color: Colors.blue,width: 2),
    disabledBorderColor: Colors.black,
    highlightedBorderColor: Colors.red,
    child: Text('OutlineButton'),
    onPressed: () {},
  );
Copy the code

RawMaterialButton

RawMaterialButton RawMaterialButton is a component created based on Semantics, Material, and InkWell. It does not use the current system theme or button theme, and is used to customize buttons or merge existing styles. RaisedButton and FlatButton are both configured with system theme and button theme based on RawMaterialButton. Related attributes can be referred to RaisedButton. Parameters are basically the same and the basic usage is as follows

Widget _RawMaterialButton = RawMaterialButton(
    onPressed: (){},
    fillColor: Colors.blue,
    child: Text('RawMaterialButton'),
  );
Copy the code

IconButton

IconButton is an IconButton and can be used as follows:

Widget _IconButton = IconButton(tooltip: 'long press to display Icons ', icon: icon (icon.person), iconSize: 30, color: Colors.red, onPressed: () {}, );Copy the code

4. Radio button (Radio)

Const Radio({Key Key, @required this.value, // Whether @required this.groupValue, @required this.onChanged, // Click the event this.mouseCursor, this.toggleable = false, this.activeColor, // Fill it with the color this.focusColor, / / focus on color enclosing hoverColor, / / hover color enclosing materialTapTargetSize, / / padding, click on the area of 48 * default to a minimum of 48, MaterialTapTargetSize. ShrinkWrap components for actual size enclosing visualDensity, / / layout is compact set enclosing focusNode, / / focus control this. An autofocus = False,// Autofocus, default is false})Copy the code

Class _RadioWidgetState extends State<RadioWidget> {var _radioGroupValue = 'language '; @override Widget build(BuildContext context) { return Container( child: Row( children: <Widget>[ Flexible( child: RadioListTile(title: Text(' Text '), value: 'Text ', activeColor:Colors. Red, groupValue: _radioGroupValue, onChanged: (value) { setState(() { _radioGroupValue = value; }); }, ), ), Flexible( child: RadioListTile( title: Text(' math '), value: 'math ', activeColor:Colors. Red, groupValue: _radioGroupValue, onChanged: (value) {setState(() {_radioGroupValue = value;});},)), Flexible(Child: RadioListTile(title: Text(' English '), value: 'English ', activeColor:Colors. Red, groupValue: _radioGroupValue, onChanged: (value) { setState(() { _radioGroupValue = value; }); }, )), ], ) ); }}Copy the code

5. Slider component

Const Slider({Key Key, @required this.value, // Current Slider value @required this.onChanged, // This. OnChangeStart,// this. OnChangeEnd,// this. Min = 0.0,// min, Default 0.0 this. Max = 1.0, // Max, The more information you need to add, the more information you need to add, and the more information you need to add, the more information you need to add, the more information you need to add, and the more information you need to add, the more information you need to add, and the more information you need to add. / / slider not across part of the color of the enclosing mouseCursor, enclosing semanticFormatterCallback, enclosing focusNode, enclosing an autofocus = false,})Copy the code

class _SliderWidgetState extends State<SliderWidget> { double _sliderValue = 0; @override Widget build(BuildContext context) { return Container( child: Column( children: <Widget>[Text(' value: $_sliderValue'), SizedBox(height: 10), Slider(value: _sliderValue, activeColor: Colors.green, inactiveColor: Colors.grey, onChanged: (v){ setState(() { _sliderValue = v; }); }, ) ], ), ); }}Copy the code

6, Switch components (Switch)

const Switch({ Key key, @required this.value, @required this.onChanged, This activeColor, / / selected the color of the circle enclosing activeTrackColor, / / selected the color of the stripes at the bottom of the enclosing inactiveThumbColor, / / not selected the color of the circle Enclosing inactiveTrackColor, / / not selected the color of the stripes at the bottom of the enclosing activeThumbImage, / / the picture of the selected circle enclosing inactiveThumbImage, / / not selected the picture of the circle Enclosing materialTapTargetSize, / / click on the area size, padded: 48 px to expand area; ShrinkWrap: Control area this.dragStartBehavior = dragStartBehavior.start,})Copy the code

Container( margin: EdgeInsets.all(30), child: Column( children: <Widget>[ Switch( value: _switchValue, activeColor: Colors.red, activeTrackColor: Colors.blue, activeThumbImage: AssetImage('images/icon1.png',), onChanged: (value){setState(() {_switchValue = value;});},), transform.scale (scale: 2.0, child: Switch(value: _switchValue, onChanged: (bool) { }), ) ], ), ), );Copy the code

7. Progress bar components

The LinearProgressIndicator progress bar component has three main components

  • LinearProgressIndicator LinearProgress bar
  • CircularProgressIndicator circular progress bar
  • CupertinoActivityIndicator IOS style progress bar
Const LinearProgressIndicator({Key Key, // [0, 1]) const LinearProgressIndicator({Key Key, // [0, 1]) // If value is null, display an animation, otherwise display a fixed double value, // Progress bar background color, Default colors ThemeData backgroundColor Color backgroundColor, / / Animation types of parameters, is used to set the Color of the progress values, the default Color ThemeData. AccentColor, if you want to custom Color, AlwaysStoppedAnimation<Color>(Color) Animation<Color> valueColor, String semanticsLabel, String semanticsValue, })Copy the code

Column(children: <Widget>[SizedBox(height: 50), LinearProgressIndicator(value: 0.3, backgroundColor: Colors.greenAccent, valueColor: AlwaysStoppedAnimation<Color>(Colors.red), ), SizedBox(height: 50), CircularProgressIndicator (value: 0.3, backgroundColor: Colors. GreenAccent valueColor: AlwaysStoppedAnimation<Color>(Colors.red), ), SizedBox(height: 50), CupertinoActivityIndicator( radius: 10, ) ], ),Copy the code

8. Picture component

The image component is one of the fundamental components of Flutter and is as essential as the text component. The Image component contains two components, Image and Icon. In essence, Icon is not an Image component, but its shape effect is similar to that of an Image. In the project, it is recommended to use the Icon component first. Icon is essentially a font, but it displays ICONS instead of words, while Image component decodes images first through the picture decoder, so Icon has the following advantages:

  • In general, ICONS are smaller than images, significantly reducing the size of your App package.
  • ICONS will not be distorted or blurred. For example, rendering a 20×20 image on a 200×200 screen will distort or blur the image, while ICONS are vector images and will not be distorted, just like fonts.
  • Multiple ICONS can be stored in a file for easy management.
  • Universal platform.

1, the Image

Flutter provides a control Image that displays an Image. And there are multiple constructors.

  • New Image Gets the Image from the ImageProvider
  • New image. asset loads the files in the Asset project resource
  • New Image.net Work retrieves web images from urls
  • New image. file Retrieves the local file Image from file
  • New image. memory Loads the Image of the Uint8List

Image support format: JPEG, PNG, GIF, animated GIF, WebP, animated WebP, BMP, WBMP

Basic usage

new Image(image: new AssetImage('images/logo.png'));
new Image(image: new NetworkImage('http://www.baid.com/sports/201/pKtl744393.jpg'))
Copy the code

When we need to use a placeholder map or display a particular image in case of an image loading error, we need to use the FadeInImage component:

new FadeInImage.assetNetwork(
    placeholder: 'images/logo.png',
    image: imageUrl,
    width: 120,
    fit: BoxFit.fitWidth,
)
new FadeInImage.memoryNetwork(
    placeholder: kTransparentImage,
    image: imageUrl,
    width: 120,
    fit: BoxFit.fitWidth,
)
Copy the code

The first method is to load a local placeholder. The second method is to load a transparent placeholder, but note that this component cannot be set to load the image displayed in error. But we can also use the CachedNetworkImage component of the third method package

new CachedNetworkImage(
    width: 120,
    fit: BoxFit.fitWidth,
    placeholder: new CircularProgressIndicator(),
    imageUrl: imageUrl,
    errorWidget: new Icon(Icons.error),
Copy the code

Image.file Loads a local Image file, such as an Image from an album

new Image.file(new File('/storage/xxx/xxx/test.jpg'))
Copy the code

Image.memory

new Image.memory(bytes),
Copy the code

Common attributes of Image

child: new Image.asset(
      'images/2-normal.png',
      alignment: Alignment.center,
      color: Colors.green,
      colorBlendMode: BlendMode.dstATop,
      fit: BoxFit.contain,
    ),
Copy the code

1. Alignment

  • TopCenter: topCenter aligned
  • TopLeft: topLeft aligned
  • TopRight: align the topRight
  • Center: align horizontally and vertically
  • CenterLeft: vertically centered horizontally aligned to the left
  • CenterRight: vertically centered horizontally aligned to the right
  • BottomCenter Aligns the bottom in the center
  • BottomLeft: Align the bottom to the left
  • BottomRight: Bottom aligned to the right

2, color and colorBlendMode

Generally used in conjunction with BlendMode, meaning mixed mode.

3, Fit pictures stretch

The FIT property controls the stretching and squeezing of images based on the parent container.

  • Boxfit.fill: Full image display, the image will be stretched and fill the parent container.
  • BoxFit. Contain: full display, display the original scale, there may be a gap.
  • Boxfit. cover: Display possibly stretched, possibly cropped, filled (the picture should fill the entire container without being distorted).
  • Boxfit. fitWidth: Width full (horizontally full), showing possible stretching, possible cutting.
  • Boxfit. fitHeight: Height full (vertical full), display may stretch, may cut.
  • Boxfit. scaleDown: similar to contain, but does not allow it to contain more than the original image.

4, whether repeat

  • ImageRepeat. Repeat: Repeat both horizontally and vertically until the entire canvas is covered.
  • ImageRepeat. RepeatX: horizontal repetition, not vertical repetition.
  • ImageRepeat. RepeatY: repeat vertically, not horizontally.

5, centerSlice

When the image needs to be stretched, the rectangle defined by centerSlice will be stretched, as we define a dot 9 file inside the image to be stretched. That is, this property is allowed only if the display size is larger than the original image size, otherwise an error will be reported.

Image image = new Image.asset(
    'imgs/logo.jpeg',
    width: 500.0,
    height: 500.0,
    fit: BoxFit.contain,
    centerSlice: new Rect.fromCircle(center: const Offset(100.0, 100.0), radius: 10.0 ),
);
Copy the code

6, matchTextDirection

Use with Directionality to reverse image display

new Directionality(
          textDirection: TextDirection.rtl,
          child: Image.asset(
            'images/dress.png',
            width: 800,
            height: 900,
            matchTextDirection: true,
          ),
        )
    Image(
          image: new AssetImage('images/dress.png'),
    )
Copy the code

7, gaplessPlayback

When the ImageProvider changes, whether the display of the original image is retained during the reload of the image. If the value is true, keep it; if it is false, leave it blank and wait for the next image to load.

2, the Icon

Icon is an Icon component. Icon does not have interactive properties. If you want to interact, you can use IconButton.

Icon(Icons.add),
Copy the code

Set the size and color of the icon:

Icon(
  Icons.add,
  size: 40,
  color: Colors.red,
)
Copy the code

9. Shape border component

Many Flutter components have a ShapeBorder property called Shape, such as Button class, Card class, etc. Shape represents the shape of the control. The system has provided many shapes for us. For components that do not have this property, Clip can be used to trim them

Border

Border allows you to set line styles for each edge individually

const Border({
    this.top = BorderSide.none,
    this.right = BorderSide.none,
    this.bottom = BorderSide.none,
    this.left = BorderSide.none,
  })
Copy the code
RaisedButton(
        shape: Border(
            top: BorderSide(color: Colors.red,width: 2)
        ),
        child: Text('Border'),
      ),
Copy the code

CircleBorder

Container(
      width: 100,
      height: 100,
      child: RaisedButton(
        shape: CircleBorder(
            side:BorderSide(color: Colors.red)
        ),
        child: Text('Border',),
      ),
    );
Copy the code

ContinuousRectangleBorder

Continuous rounded rectangles, smooth and continuous transitions between straight lines and rounded corners, will have a smaller effect than the rounded border.

Container(
      width: 300,
      height: 100,
      child: RaisedButton(
        shape: ContinuousRectangleBorder(
            side: BorderSide(color: Colors.red),
            borderRadius: BorderRadius.circular(20)),
        child: Text('ContinuousRectangleBorder',),
      ),
    );
Copy the code

RoundedRectangleBorder

The rounded rectangle

Container(
      width: 300,
      height: 100,
      child: RaisedButton(
        shape: RoundedRectangleBorder(
            side: BorderSide(color: Colors.red,width: 2),
            borderRadius: BorderRadius.circular(10)),
        child: Text('RaisedButton',),
      ),
    );
Copy the code

StadiumBorder

Shaped like a football field, round on both sides and rectangular in the middle

Container(
    width: 200,
    height: 50,
    child: RaisedButton(
      shape: StadiumBorder(),
      child: Text('RaisedButton'),
    ),
  );
Copy the code

ClipRect

The ClipRect component uses rectangular clipping sub-components, and in general, ClipRect for CustomPaint, CustomSingleChildLayout, CustomMultiChildLayout, Align, Center, OverflowBox, The SizedOverflowBox component, such as ClipRect for Align, can display only the top half, with the following code:

ClipRect(child: Align(Align: Align. TopCenter, heightFactor: 0.5, child: Container(height: 150, width: 150, child: Image.asset( 'images/cat.png', fit: BoxFit.cover, ), ), ), );Copy the code

Effect of the original image

After the shear

The clipper parameter defines the clipping rule, as described below.

ClipBehavior the clipBehavior parameter defines the clipping method, which is used only when the child control is outside the scope of the parent control. Each method is described as follows:

  • None: Unclipped, the system default, which has no performance cost if the child component does not exceed the bounds.
  • HardEdge: Clipped but not antialiased, slower than None but faster than the others.
  • AntiAlias: Clipping and anti-aliasing, this method looks smoother, faster than antiAlias with Savelayer, slower than hardEdge, commonly used for round and arc clipping.
  • AntiAliasWithSaveLayer: Clipping, anti-aliasing and a buffer. This method is slow and rarely used.

ClipRRect

The ClipRRect component can crop child components with a radius of 0 by default

ClipRRect(
    borderRadius: BorderRadius.circular(30),
    child: Container(
      height: 150,
      width: 150,
      color: red,
      child: Image.asset(
        'images/cat.png',
        fit: BoxFit.cover,
      ),
    ),
  );
Copy the code

ClipPath

ClipPath components are clipped according to the path, and our custom clipping path can also be used by the system

ClipPath.shape(
    shape: StadiumBorder(),
    child: Container(
      height: 250,
      width: 250,
      color: red,
      child: Image.asset(
        'images/cat.png',
        fit: BoxFit.cover,
      ),
    ),
  );
Copy the code

The shape parameter is of type ShapeBorder. The system has defined many shapes as follows:

  • Roundedborder: rectangleborder
  • ContinuousRectangleBorder: the transition of straight lines and smooth continuous fillet, compared with those of RoundedRectangleBorder rounded effect will be smaller.
  • StadiumBorder: Similar to the shape of a football pitch, semicircular at both ends.
  • Rectangleborder: a rectangular rectangle with bevel angles
  • CircleBorder: circle.

CustomClipper

CustomClipper is not a component, but an abstract class that can be used to draw any shape we want

class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: ClipPath( clipper: TrianglePath(), child: Container( height: 200, width: 200, color: Colors.red, ), ), ); } } class TrianglePath extends CustomClipper<Path>{ @override Path getClip(Size size) { var path = Path(); path.moveTo(size.width/2, 0); path.lineTo(0, size.height); path.lineTo(size.width, size.height); return path; } @override bool shouldReclip(CustomClipper<Path> oldClipper) { return true; }}Copy the code

10. Label Component (RawChip)

Material style label control, which is the base class of other label controls. In general, this control is not created directly. Instead, the following controls are used:

  • Chip: Chip is a simple label control that only displays information and removes related properties. It is a simplified version of RawChip
  • InputChip: Represents a piece of complex information, such as an entity (person, place, or thing) or conversation text, in a compact form
  • ChoiceChip: Allows a single selection from a set of options, creating a label similar to a radio button. Essentially, ChoiceChip is also a RawChip, and ChoiceChip itself has no radio properties.
  • FilterChip: The FilterChip can be used as a filter label
  • ActionChip: Displays a set of actions related to the main content
Chip({Key Key, this.avatar,// left Widget, @required this.label,// label this.labelStyle, this.labelPadding, this.deleteIcon// deleteIcon this.onDeleted// delete callback, Is empty does not display the delete icon enclosing deleteIconColor / / remove the color of the icon enclosing deleteButtonTooltipMessage / / delete button tip of this text. The shape / / shape enclosing clipBehavior = Clip. None, enclosing backgroundColor / / background color. This padding, / / padding enclosing materialTapTargetSize/material/delete icon click area size})Copy the code

class _ChipWidgetState extends State<ChipWidget> { int _selectIndex = 0; @override Widget build(BuildContext context) { return Wrap( spacing: 15, children: List.generate(10, (index) { return ChoiceChip( label: Text('Chip $index'), selected: _selectIndex == index, selectedColor: red, onSelected: (v) { setState(() { _selectIndex = index; }); }); }).toList(), ); }}Copy the code

Code address: github.com/SunshineBro…