Basic widget of flutter (7)

Time:2020-1-17

Basic widget of flutter

Foreword 1: I will update some columns of flutter text tutorials in succession in the next period

Update progress:At least two articles per week;

Update location:First appeared in the public number, and the second day was updated in nuggets, thoughts and developers’ headlines.

More communication:You can add my wechat 372623326 and follow my micro blog: Code why

I hope you canHelp forward, click to seeGive me more creative power.

Foreword 2: this chapter originally intended to explain the rendering principle of flutter, but too much explanation of the principle content at the beginning of learning is not conducive to the quick start and hands-on, making some effective content;

So, I’m going to change my thinking, first explain the usage of some components, let you get used to the development process and mode of flutter, and then go back to consolidate the theoretical knowledge;

In addition, when explaining these widgets, I don’t intend to list all the attributes one by one, because they are meaningless and can’t be remembered;

I plan to have a topic laterAbout flutter layoutYes, we will select some good-looking layout interfaces to complete with you: meituan page, Jingdong page, station B page, etc. some properties that I haven’t mentioned at present will be explained later;

1. Text widget

In Android, we use textview, and in IOS, we use uilabel to display text;

In flutter, we use the text component to control how the text is displayed;

1.1. Common text display

In flutter, we can divide the text control display into two categories:

  • Parameters to control text layout:For example, text alignment textalign, text typesetting direction textdirection, text display Max lines, text truncation rule overflow and so on are all parameters in the constructor;
  • Parameters that control the text style:For example, font name fontfamily, font size fontsize, text color, text shadow and so on. These parameters are uniformly encapsulated in the parameter style in the constructor;

Let’s take a look at the use of some of these properties:

class MyHomeBody extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(
      "Settle the storm" Su Shi: don't listen to the sound of beating leaves through the forest. Why not sing and walk slowly. \N bamboo stick and shoes are better than horses. Who is afraid? A drizzle of smoke and rain will last forever. "
      style: TextStyle(
        fontSize: 20,
        color: Colors.purple
      ),
    );
  }
}

The display effect is as follows:

Basic widget of flutter (7)

We can change the layout of text through some properties:

  • Textalign: text alignment, such as textalign.center
  • Maxlines: the maximum number of displayed lines, such as 1
  • Overflow: display mode of overflow part, such as textoverflow.ellipsis
  • Textscalefactor: controls text scaling, such as 1.24

The code is as follows:

class MyHomeBody extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(
      "Settle the storm" Su Shi: don't listen to the sound of beating leaves through the forest. Why not sing and walk slowly. \N bamboo stick and shoes are better than horses. Who is afraid? A drizzle of smoke and rain will last forever. "
      Textalign: textalign.center, // center all content
      Maxlines: 3, // obviously. "Deleted
      Overflow: textoverflow. Ellipsis, // overflow part is displayed
//      textScaleFactor: 1.25,
      style: TextStyle(
        fontSize: 20,
        color: Colors.purple
      ),
    );
  }
}

Basic widget of flutter (7)

1.2. Rich text display

For the text shown above, we all apply the same style. What if we want to give them different styles?

  • For example, “dingfengbo” I hope the font is bigger, black and bold;
  • For example, Su Shi, I hope it is red font;

If we want to show this hybrid style, we can use sharding to operate (in Android, we can use spannablestring, in IOS, we can use nsattributedstring to complete, just understand)

The code is as follows:

class MyHomeBody extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text.rich(
      TextSpan(
        children: [
          Textspan (text: "calm the wind", style: TextStyle (fontsize: 25, FontWeight: FontWeight. Bold, color: colors. Black)),
          Textspan (text: "sushi", style: TextStyle (fontsize: 18, color: colors. Redaccess)),
          Textspan (text: "\ n don't listen to the sound of beating leaves through the forest. Why not sing and walk slowly. \N bamboo stick and shoes are better than horses. Who is afraid? A drizzle of smoke and rain will last forever. ""
        ],
      ),
      style: TextStyle(fontSize: 20, color: Colors.purple),
      textAlign: TextAlign.center,
    );
  }
}

Basic widget of flutter (7)

2、 Button widget

2.1. Button Foundation

A variety of button widgets are provided in the material widget library, such as floatingactionbutton, raisedbutton, flatbutton, and outlinebutton

Let’s show them directly:

class MyHomeBody extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        FloatingActionButton(
          child: Text("FloatingActionButton"),
          onPressed: () {
            print("FloatingActionButton Click");
          },
        ),
        RaisedButton(
          child: Text("RaisedButton"),
          onPressed: () {
            print("RaisedButton Click");
          },
        ),
        FlatButton(
          child: Text("FlatButton"),
          onPressed: () {
            print("FlatButton Click");
          },
        ),
        OutlineButton(
          child: Text("OutlineButton"),
          onPressed: () {
            print("OutlineButton Click");
          },
        )
      ],
    );
  }
}

Basic widget of flutter (7)

2.2. Custom style

We use the default style for the previous buttons. We can change the style of the buttons through some properties

RaisedButton(
  Child: text ("agreement", style: TextStyle (color: colors. White)),
  Color: colors.orange, // button color
  Highlightcolor: colors. Orange [700], // press to highlight a color
  Shape: roundedrectangle border (border radius: border radius. Circular (20)), // implementation of fillet
  onPressed: () {
    Print (the "agreement");
  },
)

Basic widget of flutter (7)

In fact, there is a common attribute here: elevation, which is used to control the size of shadows. This attribute can be found in many places. You can demonstrate it yourself

3、 Picture widget

Pictures can make our application more colorful. Image component is used in flutter

Image component has many constructors. Here we mainly learn two:

  • Image.assets: load the local resource image;
  • Image.network: load the pictures in the network;

3.1. Loading network pictures

Relatively speaking, it’s easier to load network pictures in flutter. It doesn’t need any configuration to directly enter the URL, so let’s take a look at how to load network pictures in flutter first.

Let’s first look at the properties of image that can be set:

const Image({
  ...
  This.width, // the width of the picture
  This.height, // image height
  This.color, // the mixed color value of the picture
  This.colorblendmode, // mixed mode
  This.fit, // zoom mode
  This.alignment = alignment.center, // alignment
  This.repeat = imagerepeat.norepeat, // repeat mode
  ...
})
  • widthheight: used to set the width and height of a picture. When the width and height are not specified, the picture will display its original size as much as possible according to the limit of the current parent container. If onlywidthheightThe other attribute will be scaled by default, but you can use thefitProperty to specify the adaptation rule.
  • fit: this attribute is used to specify the adaptation mode of the picture when the display space of the picture and the size of the picture itself are different. The adaptation mode isBoxFitAs defined in, it is an enumeration type with the following values:

    • fill: it will stretch and fill the display space, the aspect ratio of the picture itself will change, and the picture will be deformed.
    • cover: the display space will be filled in the middle after the image is enlarged according to the aspect ratio. The image will not be deformed, and the part beyond the display space will be clipped.
    • contain: This is the default adaptation rule of the picture. The picture will be zoomed to adapt to the current display space without changing its aspect ratio.
    • fitWidth: the width of the picture will be scaled to the width of the display space, the height will be scaled, and then the picture will not be deformed, and the part beyond the display space will be clipped.
    • fitHeight: the height of the picture will be scaled to the height of the display space, the width will be scaled, and then the picture will be centered, the picture will not be deformed, and the part beyond the display space will be clipped.
    • none: there is no adaptation strategy for pictures. Pictures will be displayed in the display space. If the picture is larger than the display space, only the middle part of the picture will be displayed in the display space.
  • colorandcolorBlendMode: each pixel can be color mixed when the picture is drawn,colorSpecifies the blend color, andcolorBlendModeSpecify mixed mode;
  • repeat: when the size of the picture itself is smaller than the display space, specify the repetition rule of the picture.

Let’s walk through some of these properties:

  • Note that I use a container here. You can understand it as a uiview or view, which is a container;
  • Later I will talk about the use of this component;
class MyHomeBody extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: Image.network(
          "http://img0.dili360.com/ga/M01/48/3C/wKgBy1kj49qAMVd7ADKmuZ9jug8377.tub.jpg",
          alignment: Alignment.topCenter,
          repeat: ImageRepeat.repeatY,
          color: Colors.red,
          colorBlendMode: BlendMode.colorDodge,
        ),
        width: 300,
        height: 300,
        color: Colors.yellow,
      ),
    );
  }
}

Basic widget of flutter (7)

3.2. Load local image

It’s a little bit troublesome to load the local image. You need to import the image and configure it

class MyHomeBody extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 300,
        height: 300,
        color: Colors.yellow,
        child: Image.asset("images/test.jpeg"),
      ),
    );
  }
}

Basic widget of flutter (7)

3.3. Realize fillet image

Some widgets are also used to achieve fillet effect in flutter.

3.3.1. Achieve rounded head image

Mode 1: circleavatar

Circleavatar can realize rounded head image or add a subwidget:

const CircleAvatar({
  Key key,
  This.child, // child widget
  This.backgroundcolor, // background color
  This.backgroundimage, // background image
  This.foregroundcolor, // foreground color
  This.radius, // radius
  This.minradius, // minimum radius
  This.maxradius, // maximum radius
})

Let’s achieve a round head:

  • Note 1: we use network image here, because backgroundimage requires us to pass in an imageprovider;

    • Imageprovider is an abstract class. In fact, all image objects we created earlier containimageProperty, which is an imageprovider
  • Note 2: Here I also added a text inside, but I wrapped a container outside the text;

    • The purpose of the container is to control the position adjustment of the text;
class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: CircleAvatar(
        radius: 100,
        backgroundImage: NetworkImage("https://tva1.sinaimg.cn/large/006y8mN6gy1g7aa03bmfpj3069069mx8.jpg"),
        child: Container(
          alignment: Alignment(0, .5),
          width: 200,
          height: 200,
          Child: text ("soldier will")
        ),
      ),
    );
  }
}

Basic widget of flutter (7)

Mode 2: clipoval

Clipoval can also implement rounded heads, and is usually used when only heads are available

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: ClipOval(
        child: Image.network(
          "https://tva1.sinaimg.cn/large/006y8mN6gy1g7aa03bmfpj3069069mx8.jpg",
          width: 200,
          height: 200,
        ),
      ),
    );
  }
}

Basic widget of flutter (7)

Implementation mode 3: container + boxdecoration

This way, we will talk about it when we talk about container

3.3.2. Realize fillet image

Mode 1: cliprrect

Cliprrect is used to achieve the fillet effect. You can set the size of the fillet.

The implementation code is as follows, very simple:

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: Image.network(
          "https://tva1.sinaimg.cn/large/006y8mN6gy1g7aa03bmfpj3069069mx8.jpg",
          width: 200,
          height: 200,
        ),
      ),
    );
  }
}

Basic widget of flutter (7)

Mode 2: container + boxdecoration

This will be explained later when we explain the container

4、 Form widget

One of the interactions with users is the input box, such as registration, login and search. We collect the input of users and submit it to the server.

4.1. Use of textfield

4.1.1. Introduction to textfield

Textfield is used to receive text input from users. It provides many properties. Let’s look at the source code:

  • But we don’t need to learn one by one. When we use a function, we need to check whether it contains a property
const TextField({
  Key key,
  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.obscureText = false,
  this.autocorrect = true,
  this.maxLines = 1,
  this.minLines,
  this.expands = false,
  this.maxLength,
  this.maxLengthEnforced = true,
  this.onChanged,
  this.onEditingComplete,
  this.onSubmitted,
  this.inputFormatters,
  this.enabled,
  this.cursorWidth = 2.0,
  this.cursorRadius,
  this.cursorColor,
  this.keyboardAppearance,
  this.scrollPadding = const EdgeInsets.all(20.0),
  this.dragStartBehavior = DragStartBehavior.start,
  this.enableInteractiveSelection = true,
  this.onTap,
  this.buildCounter,
  this.scrollController,
  this.scrollPhysics,
}) 

Let’s learn some common attributes:

  • Some properties are simple:keyboardTypeType of keyboard,styleSet the style,textAlignText alignment,maxLengthThe maximum number of display lines, etc;
  • decoration: used to set input box related styles

    • Icon: set the icon displayed on the left
    • LabelText: text with a prompt above the input box
    • Hinttext: display the placeholder text of the prompt
    • Border: the border of the input box. There is a border at the bottom by default, which can be deleted through inputborder.none
    • Filled: whether to fill in the input box. The default value is false
    • Fillcolor: the color of the input box
  • controller
  • onChanged: listen for the change of input box content, and pass in a callback function
  • onSubmitted: when you click down in the lower right corner of the keyboard, a function will be called back

4.1.2. Textfield style and monitoring

Let’s demonstrate textfield’s decoration property and listening:

class HomeContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          TextFieldDemo()
        ],
      ),
    );
  }
}

class TextFieldDemo extends StatefulWidget {
  @override
  _TextFieldDemoState createState() => _TextFieldDemoState();
}

class _TextFieldDemoState extends State<TextFieldDemo> {
  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: InputDecoration(
        icon: Icon(Icons.people),
        labelText: "username",
        Hinttext: "please enter user name",
        border: InputBorder.none,
        filled: true,
        fillColor: Colors.lightGreen
      ),
      onChanged: (value) {
        print("onChanged:$value");
      },
      onSubmitted: (value) {
        print("onSubmitted:$value");
      },
    );
  }
}

Basic widget of flutter (7)

4.1.3. Controller of textfield

We can add a controller to textfield, which can be used to set the initial value of the text, or to monitor the change of the text;

In fact, if we don’t provide a controller for textfield, then the flutter will create a texteditingcontroller by default. This conclusion can be obtained by reading the source code:

@override
  void initState() {
    super.initState();
    //... other codes
    if (widget.controller == null)
      _controller = TextEditingController();
  }

We can also create a controller to control some content:

class _TextFieldDemoState extends State<TextFieldDemo> {
  final textEditingController = TextEditingController();

  @override
  void initState() {
    super.initState();

    //1. Set default value
    textEditingController.text = "Hello World";

    //2. Monitor text box
    textEditingController.addListener(() {
      print("textEditingController:${textEditingController.text}");
    });
  }
    
  //... omit build method
}

Basic widget of flutter (7)

4.2. Use of form form

When we develop registration and login pages, there are usually multiple forms that need to obtain content or perform some validation at the same time. If we verify each textfield separately, it is a more troublesome thing.

After the development of the front-end, we know that we can put multiple input tags in one form, and flutter also uses this idea for reference: we can group the input boxes through the form, and perform some unified operations.

4.2.1. Basic use of form form

The form form is also a widget, which can be put into our input box.

But the input box in the form form must be of type formfield

  • We see that the textfield we just learned is inherited from statefulwidget, not a formfield type;
  • We can use textformfield, which is similar to textfield and inherits from formfield;

We use the package of form to realize a registered page:

class FormDemo extends StatefulWidget {
  @override
  _FormDemoState createState() => _FormDemoState();
}

class _FormDemoState extends State<FormDemo> {
  @override
  Widget build(BuildContext context) {
    return Form(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          TextFormField(
            decoration: InputDecoration(
              icon: Icon(Icons.people),
              LabelText: "user name or mobile number"
            ),
          ),
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(
              icon: Icon(Icons.lock),
              LabelText: "password"
            ),
          ),
          SizedBox(height: 16,),
          Container(
            width: double.infinity,
            height: 44,
            child: RaisedButton(
              color: Colors.lightGreen,
              Child: text ("register", style: TextStyle (fontsize: 20, color: colors. White),),
              onPressed: () {
                Print ("click the register button");
              },
            ),
          )
        ],
      ),
    );
  }
}

Basic widget of flutter (7)

4.2.2. Save and obtain form data

With the form, when we click to register, we can get and save the data in the form at the same time. How can we do this?

  • 1. You need to listen to the click of the registration button, which can be done in the incoming callback of onppressed that we have listened to before. (of course, if there is too much nesting, we can extract it into a separate method later.)
  • 2. When listening to the button click, obtainUser nameandPasswordForm information for.

How to obtain at the same timeUser nameandPasswordForm information for?

  • If we callState object of formThe save method of will call the onsave callback of textformfield put in the form:
TextFormField(
  decoration: InputDecoration(
    icon: Icon(Icons.people),
    LabelText: "user name or mobile number"
  ),
  onSaved: (value) {
    Print ("Username: $value");
  },
),
  • But do we have any way to getForm objectTo call its save method?

Knowledge point: how to get a state object of a statefulwidget through a reference in flutter?

Answer: you can bind a globalkey.

Basic widget of flutter (7)

Case code drill:

class FormDemo extends StatefulWidget {
  @override
  _FormDemoState createState() => _FormDemoState();
}

class _FormDemoState extends State<FormDemo> {
  final registerFormKey = GlobalKey<FormState>();
  String username, password;

  void registerForm() {
    registerFormKey.currentState.save();

    print("username:$username password:$password");
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: registerFormKey,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          TextFormField(
            decoration: InputDecoration(
              icon: Icon(Icons.people),
              LabelText: "user name or mobile number"
            ),
            onSaved: (value) {
              this.username = value;
            },
          ),
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(
              icon: Icon(Icons.lock),
              LabelText: "password"
            ),
            onSaved: (value) {
              this.password = value;
            },
          ),
          SizedBox(height: 16,),
          Container(
            width: double.infinity,
            height: 44,
            child: RaisedButton(
              color: Colors.lightGreen,
              Child: text ("register", style: TextStyle (fontsize: 20, color: colors. White),),
              onPressed: registerForm,
            ),
          )
        ],
      ),
    );
  }
}

Basic widget of flutter (7)

4.2.3. Verify the filled in form data

In the form, we can addValidator, if some specific rules are not met, give the user certain prompt information

For example, we need rules for account and password: account and password cannot be empty.

The whole verification process can be completed as follows:

  • 1. Add the callback function of validator for textformfield;
  • 2. Call the validate method of the state object of the form, and the function passed in by the validator will be called back;

Basic widget of flutter (7)

You can also add a property for textformfield: autovalidate

  • It does not need to call the validate method, which will automatically verify whether it meets the requirements;

Basic widget of flutter (7)

Note: all contents start with the public number. In addition to Flutter, other technical articles will be updated. TypeScript, React, Node, uniapp, mpvue, data structure and algorithm will also update some of their own learning experiences. Welcome everyone’s attention.

Basic widget of flutter (7)

Recommended Today

Summary: NPM common commands and operations

The full name of NPM is (node package manager), which is a package management and distribution tool installed with nodejs. It is very convenient for JavaScript developersDownload, install, upload and manage installed packages。 First of all, the following variables will be used: < name > | < PKG > module name < version > version […]