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.dart
By default, some simple UI styles are generated. Run them to see what they look likeiPhone
Simulator).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 itWidget
Just to play around and see what happens, and just to keep the code from getting too messy, here’s oneWidget
To create adart
Separate 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.dart
theContainer
Replace 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 setmaxLine
andoverflow
Properties. Click when doneHot reload
And 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 codeRichText
In a nestedTextSpan
Just tweak it a little and run it, and you get a simple rich text effect.
Container
Create another onecontainer_demo.dart
File, return oneContainer
theWidget
And then introduce tomain
thebody
In, we giveContainer
Set a color and run.You can see the wholebody
beContainer
Full. It’s an elastic layout. We’re inContainer
Put inside aRow
And 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 beforebody
theContainer
It’s getting smaller, so ifContainer
Not setting the width and height is affected by the size of the child parts. And let’s seeContainer
Properties:
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 abovepadding
andmargin
To see the effect, the code is as follows:redContainer
The distance from the plus icon is 30, which is the inside marginpadding
Properties, redContainer
The distance from yellow is 20, which is the marginmargin
Properties.
alignment
The aboveContainer
Nested insideRow
.Row
It’s all across the screen. Now delete the previous oneRow
In theContainer
Put aText
And then set it’salignment
(Values range from -1 to 1), run it again to see what happens.throughalignment
You 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 becauseRow
It’s going to fill the landscape, so forRow
foralignment
Set up thex
The axial direction is invalid, also forColumn
Set up they
The axial direction is invalid.
Column
Column
It’s a vertical layoutWidget
, vertical fill the screen, horizontal will automatically layout according to the size of the sub-parts, the above codeRow
toColumn
And run.
Stack
Stack
It’s a cascading layoutWidget
, from the inner layer forget the outer layout, if the size of each sub-component is the same, the outer layerWidget
It will cover the inner layerWidget
, the same code as above, but changed toStack
And run.You can see that only the last additions are displayedalarm
theIcon
ICONS, we put eachThe child widgets
It’s a little bit more intuitive.After changing the size, you can see thatStack
The 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,start
Is the default starting direction,end
I start at the end,center
It’s in the middle. We take theRow
As an example, run each of these three ways to see the effect.Now let’s seespaceBetween
,spaceAround
,spaceEvenly
What 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 withcrossAxisAlignment
Run related properties to see the effect.The first three properties work fine, but insteadbaseline
Run error, herebaseline
Properties to matchRow
The component’stextBaseline
Attribute 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 sumend
Same effect.At this point we putIcon
toText
“, 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 cooperatetextBaseline
Use align the bottom of the text.
Expanded
Now let’s take the previousRow
thechildren
The subcomponents are nested inExpanded
Look 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.
Text
Control, as well asRichText
Use of rich text controls.Container
The use of,Alignment
The parameters of thex
andy
.Row
andColumn
The concepts of principal axis and cross axis are recognized.Stack
The use of cascading display.Expanded
, populate widgets that can fill the parent component.