Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

From the previous article we learned about the setup of the Flutter environment and the simple use of the ListView. In this article we will continue to familiarize ourselves with some other widgets.

Engineering to create

To create a project, you can use Android Studio or the command line to create the project directory path. The command line is as follows:

# I: iOS # objc: Select objective-C, not select language here, iOS defaults to Swift, Android defaults to Kotlin flutter create -i objc flutter_demoCopy the code

The project will be created inlib/main.dartBy default, some simple UI styles are generated. Run them to see what they look likeiPhoneSimulator).From the results, you can see text and buttons displayed, and the button count increases when clicked. So let’s get rid of the original code and customize itWidgetJust to play around and see what happens, and just to keep the code from getting too messy, here’s oneWidgetTo create adartSeparate files.

Commonly used widgets

Create another views directory in the lib file directory. Dart code. Dart code.

import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Flutter Demo'), ), body: Container(), ), ); }}Copy the code

Text

Dart creates a text_widget.dart file for the StatelessWidget in the views file. First look at the properties of Text.

const Text(
  String 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

You can set the style, alignment, Text orientation, maximum number of lines, and so on. You can simply set some properties

import 'package:flutter/material.dart'; class TextWidget extends StatelessWidget { const TextWidget({Key? key}) : super(key: key); @Override Widget Build (BuildContext Context) {return const Text('Flutter is a framework published by Google for creating cross-platform, high-performance mobile applications. Flutter, like Qt Mobile, does not use native controls. Instead, Flutter implements a self-drawing engine that uses its own layout and drawing system. ', textAlign: textalign.center, style: TextStyle(fontSize: 16.0, color: color.red,); }}Copy the code

themain.darttheContainerReplace the one you just createdTextWidget, and then run.If you want to set the maximum number of lines, then use redundant.The mode can be setmaxLineandoverflowProperties. Click when doneHot reloadAnd you can see the effect.

RichText

RichText is often used in text styles. The Widget that provides RichText in Flutter is RichText. Take a look at the RichText property definition

RichText({ Key? key, required this.text, this.textAlign = TextAlign.start, this.textDirection, this.softWrap = true, This. Overflow = Textoverflow. clip, this.textScaleFactor = 1.0, this.maxLines, this.locale, this.strutStyle, this.textWidthBasis = TextWidthBasis.parent, this.textHeightBehavior, })Copy the code

TextSpan, the difference between TextSpan and text is that it has a children property, so you can nest it, so you can style the text differently.

const TextSpan({
  this.text,
  this.children,
  TextStyle? style,
  this.recognizer,
  MouseCursor? mouseCursor,
  this.onEnter,
  this.onExit,
  this.semanticsLabel,
  this.locale,
  this.spellOut,
})
Copy the code

I’m going to use that codeRichTextIn a nestedTextSpanJust tweak it a little and run it, and you get a simple rich text effect.

Container

Create another onecontainer_demo.dartFile, return oneContainertheWidgetAnd then introduce tomainthebodyIn, we giveContainerSet a color and run.You can see the wholebodybeContainerFull. It’s an elastic layout. We’re inContainerPut inside aRowAnd then you can nest itIcon, the code is as follows:

import 'package:flutter/material.dart'; class ContainerDemo extends StatelessWidget { const ContainerDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( color: Colors.yellow, child: Row( children: [ Container( color: Colors.red, child: const Icon(Icons.add), ), ], ), ); }}Copy the code

Run it again.You can see the yellow filled up beforebodytheContainerIt’s getting smaller, so ifContainerNot setting the width and height is affected by the size of the child parts. And let’s seeContainerProperties:

Container({
  Key? key,
  this.alignment,
  this.padding,
  this.color,
  this.decoration,
  this.foregroundDecoration,
  double? width,
  double? height,
  BoxConstraints? constraints,
  this.margin,
  this.transform,
  this.transformAlignment,
  this.child,
  this.clipBehavior = Clip.none,
}) 
Copy the code
margin & padding

Set it up again in the code abovepaddingandmarginTo see the effect, the code is as follows:redContainerThe distance from the plus icon is 30, which is the inside marginpaddingProperties, redContainerThe distance from yellow is 20, which is the marginmarginProperties.

alignment

The aboveContainerNested insideRow.RowIt’s all across the screen. Now delete the previous oneRowIn theContainerPut aTextAnd then set it’salignment(Values range from -1 to 1), run it again to see what happens.throughalignmentYou can set the coordinate points of elements.

Row

Dart creates a row_demo.dart, places three ICONS in the Row, and sets the alignment to (0, 0).

import 'package:flutter/material.dart'; class RowDemo extends StatelessWidget { const RowDemo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( alignment: const Alignment(0, 0), color: Colors.yellow, child: Row( children: [ Container( child: const Icon(Icons.add, size: 45,), color: Colors.red, ), Container( child: const Icon(Icons.ac_unit, size: 45,), color: Colors.blue, ), Container( child: const Icon(Icons.access_alarm, size: 45,), color: Colors.white, ), ], ), ); }}Copy the code

So let’s run it and see what happensYou can see the icon is left in landscape, and portrait is center becauseRowIt’s going to fill the landscape, so forRowforalignmentSet up thexThe axial direction is invalid, also forColumnSet up theyThe axial direction is invalid.

Column

ColumnIt’s a vertical layoutWidget, vertical fill the screen, horizontal will automatically layout according to the size of the sub-parts, the above codeRowtoColumnAnd run.

Stack

StackIt’s a cascading layoutWidget, from the inner layer forget the outer layout, if the size of each sub-component is the same, the outer layerWidgetIt will cover the inner layerWidget, the same code as above, but changed toStackAnd run.You can see that only the last additions are displayedalarmtheIconICONS, we put eachThe child widgetsIt’s a little bit more intuitive.After changing the size, you can see thatStackThe subcomponents are stacked to display.

Principal axis and cross axis

Row, Column, and Stack all have the concept of mainAxisAlignment and crossAxisAlignment attributes. In horizontal layouts, the main axis is to the right, in vertical layouts, the main axis is to the down, and in cascading layouts, the main axis is to the outside. The cross axis is the vertical direction of the principal axis.

mainAxisAlignment

Take a look at the definition of MainAxisAlignment.

enum MainAxisAlignment {
  start,
  end,
  center,
  spaceBetween,
  spaceAround,
  spaceEvenly,
}
Copy the code

The first three are easy to understand,startIs the default starting direction,endI start at the end,centerIt’s in the middle. We take theRowAs an example, run each of these three ways to see the effect.Now let’s seespaceBetween,spaceAround,spaceEvenlyWhat are the effects of?According to the running effect, it can be seen:

  • spaceBetween: The remaining space is evenly distributed between the widgets.
  • spaceAround: The remaining space is evenly distributed around the widgets.
  • spaceEvenly: Divide the rest of the space evenly with the widgets.
crossAxisAlignment

Take a look at the definition of CrossAxisAlignment.

enum CrossAxisAlignment {
  start,
  end,
  stretch,
  baseline,
}
Copy the code

Directly coupled withcrossAxisAlignmentRun related properties to see the effect.The first three properties work fine, but insteadbaselineRun error, herebaselineProperties to matchRowThe component’stextBaselineAttribute use, the code is as follows:

Widget build(BuildContext context) {
  return Container(
    alignment: const Alignment(0, 0),
    color: Colors.yellow,
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      crossAxisAlignment: CrossAxisAlignment.baseline,
      textBaseline: TextBaseline.alphabetic,
      children: [
        Container(
          child: const Icon(Icons.add, size: 120,),
          color: Colors.red,
        ),
        Container(
          child: const Icon(Icons.ac_unit, size: 60,),
          color: Colors.blue,
        ),
        Container(
          child: const Icon(Icons.access_alarm, size: 30,),
          color: Colors.white,
        ),
      ],
    ),
  );
}
Copy the code

Run it again and you can see the sumendSame effect.At this point we putIcontoText“, and set the text size to different, and then see the effect.You can see the bottom alignment of all the text.

  • start: Align the start position.
  • end: Align the end position.
  • stretch: Cross axes fill the screen.
  • baseline: Need to cooperatetextBaselineUse align the bottom of the text.

Expanded

Now let’s take the previousRowthechildrenThe subcomponents are nested inExpandedLook at the effect.Child controls fill the main axis, if the main axis does not fit will automatically wrap.

  • Expanded: There will be no clearance left in the spindle direction and will be Expanded and stretched.

conclusion

In this article, I have learned about the common widgets of Flutter. I also looked at the changes in the properties of different widgets after they were actually implemented. I made a brief summary based on the usage of these widgets.

  • TextControl, as well asRichTextUse of rich text controls.
  • ContainerThe use of,AlignmentThe parameters of thexandy.
  • RowandColumnThe concepts of principal axis and cross axis are recognized.
  • StackThe use of cascading display.
  • Expanded, populate widgets that can fill the parent component.