当前位置:网站首页>Flutter entry and advanced tour (6) Layout Widget

Flutter entry and advanced tour (6) Layout Widget

2022-08-09 13:24:00 Xie Dong_

往期回顾:

        The previous period of column for everyone to learn up is easy and happy,We simply metflutter这门新技术,And try to learn likeText、Image、TextField几个简单的Widget,And we use these a fewWidgetTo do some simple interaction,If we didn't pay attention toWidgetThe display of the location and layout,We just let him show,And then if you want to put theseWidgetCombined in a rendering to the whole mobile phone screen,We need a reasonable selection of the container to package theseWidget,Or let theWidgetComfortable are arranged in a proper container,As we are doing nativeandroid时,如果UINeed to draw on a horizontal or verticalview排列,我们会选用LinearLayoutRather than chooseFrameLayout,同理在FlutterOn the layout of the emissions we should also be appropriate to select the correct container.

      在FlutterAlso provide us with a variety of different scenarioslayout,我们可以根据UIThe layout needs to choose differentlayoutTo complete our onUI的绘制,在这些layout中,有些layoutReference to the box layout model of front end,Some completely with nativeandroid思想一致,So for us to study it is not so abstract,Below I listed a few commonly usedlayout,And an example with everyone to seeFlutterWhat was doneWidget的布局的.

Flutter中容器:

  • Row、Column
  • Stack
  • Center
  • Container
  • ListView
  • Align
  • Padding
  • SizedBox
  • AspectRadio
  • DecoratedBox
  • Opactity

Below I list several commonLayout使用场景

1.Row、Column

These two kinds of layout is almost the same,So I put them in a lecture,First look at the source code to the description of both

class Column extends Flex {
  /// Creates a vertical array of children.


class Row extends Flex {
  /// Creates a horizontal array of children.
  ///

We learn from source code comments are both a cheng fangchildren widget的array,The difference is one is in a horizontal direction(horizontal),The other is a vertical direction(vertical)

Due to the similar,我们只拿Row做讲解,To a piece of analysisRow构造方法,Take a look at what give us customizable properties

Row({
  Key key,
  MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
  MainAxisSize mainAxisSize = MainAxisSize.max,
  CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
  TextDirection textDirection,
  VerticalDirection verticalDirection = VerticalDirection.down,
  TextBaseline textBaseline,
  List<Widget> children = const <Widget>[],
})

1.1 属性解析

1.1.1 MainAxisAlignment:

主轴方向上的对齐方式,会对child的位置起作用,默认是start.其中MainAxisAlignment枚举值:

  • center:将children放置在主轴的中心;
  • end:将children放置在主轴的末尾;
  • spaceAround:将主轴方向上的空白区域均分,使得children之间的空白区域相等,但是首尾child的空白区域为1/2;
  • spaceBetween:将主轴方向上的空白区域均分,使得children之间的空白区域相等,首尾child都靠近首尾,没有间隙;
  • spaceEvenly:将主轴方向上的空白区域均分,使得children之间的空白区域相等,包括首尾child;
  • start:将children放置在主轴的起点;

其中spaceAround、spaceBetween以及spaceEvenly的区别,就是对待首尾child的方式.其距离首尾的距离分别是空白区域的1/2、0、1.

1.1.2 MainAxisSize

在主轴方向占有空间的值,默认是max.MainAxisSize的取值有两种:

  • max:根据传入的布局约束条件,最大化主轴方向的可用空间;
  • min:与max相反,是最小化主轴方向的可用空间;

1.1.3 CrossAxisAlignment

children在交叉轴方向的对齐方式,与MainAxisAlignment略有不同.CrossAxisAlignment枚举值有如下几种:

  • baseline:在交叉轴方向,使得children的baseline对齐;
  • center:children在交叉轴上居中展示;
  • end:children在交叉轴上末尾展示;
  • start:children在交叉轴上起点处展示;
  • stretch:让children填满交叉轴方向;

1.1.4TextDirection

阿拉伯语系的兼容设置,一般无需处理.

1.1.5 VerticalDirection

定义了children摆放顺序,默认是down.VerticalDirection枚举值有两种:

  • down:从top到bottom进行布局;
  • up:从bottom到top进行布局.

top对应Row以及Column的话,就是左边和顶部,bottom的话,则是右边和底部.

1.1.6 TextBaseline

使用的TextBaseline的方式,有两种,前面已经介绍过.

Dry said so much is really boring,A figure on the intuitive feelRow,我在RowHorizontal arrangement inside a fewRaisedButton

效果图:

样例代码:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new LayoutDemo()));
}

class LayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("水平方向布局"),
      ),

      //布局方向  Row:水平布局 Column:垂直布局
      body: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          new RaisedButton(
            onPressed: () {
              print('点击红色按钮');
            },
            color: const Color(0xffff0000),
            child: new Text('红色按钮'),
          ),
          new RaisedButton(
            onPressed: () {
              print("点击蓝色按钮");
            },
            color: const Color(0xff000099),
            child: new Text('蓝色按钮'),
          ),
          new RaisedButton(
            onPressed: () {
              print("点击粉色按钮");
            },
            color: const Color(0xffee9999),
            child: new Text('粉色按钮'),
          )
        ],
      ),
    );
    ;
  }
}

cloumn与Row大同小异,读者可自行测试,I won't post code demonstrates in detail.Below us to see anotherlayout方式.

2.Stack

StackThe cascade layout,跟原生Android里面的FrameLayout如出一辙,Can the childwidget层叠排列.If you do not specify a display position,The default layout in the upper left corner,If you want to subspace is displayed in the specific location,我们可以通过PositionedControls the parcelwidget,Then according to the positioning of child controlstop、right、bottom、leftAttribute to place them inStack的合适位置上.

Stack布局效果图:

上述效果图样例代码:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new StackLayoutDemo()));
}

class StackLayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('层叠布局'),
        ),
        body: new Center(
          child: new Stack(
            children: <Widget>[
              new Image.network(
                'https://avatar.csdn.net/6/0/6/1_xieluoxixi.jpg',
                scale: 0.5,
              ),
              new Positioned(
                  left: 35.0,
                  right: 35.0,
                  top: 45.0,
                  child: new Text(
                    'The second content area',
                    style: new TextStyle(
                      fontSize: 20.0,
                      fontFamily: 'serif',
                    ),
                  )),
              new Positioned(
                  left: 55.0,
                  right: 55.0,
                  top: 55.0,
                  child: new Text(
                    '第三层 this is the third child',
                    style: new TextStyle(
                      fontSize: 20.0,
                      color: Colors.blue,
                      fontFamily: 'serif',
                    ),
                  ))
            ],
          ),
        ));
  }
}

 

3.Center

CenterLayout using simpler,场景也比较单一,Generally used to help other childrenwidget布局,Covering thechild widgetDisplayed in the center of the upper layout.上述StackLayout in useCenterLet it shows in the center of the screen is,看下官方对Center的解释:

class Center extends Align {
  /// Creates a widget that centers its child.
  const Center({ Key key, double widthFactor, double heightFactor, Widget child })
    : super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);
}

比较简单直接,I won't post rendering,Readers can usecenter包裹子widget做测试,So intuitive experiencecenter布局.

//CenterBoth the center positioning control,Can child controls on its internal center.
class CenterLayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('中心布局'),
      ),
      body: new Center(
        child: new Text('I'm in the middle of the screen'),
      ),
    );
  }
}

4.ListView

ListviewUsage scenarios with nativeAndroid一样,Are used to show a long list of data,Also we use in the development of morewidget之一,本章节主要分析layout,Is not in detail analysis,Take you under the simple understandingListView的用法,We also took a follow-up chapters explainListView,跟listView类似的还有GridView.

ListView效果图:

The above implementation sample code:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new ListViewLayoutDemo()));
}

class ListViewLayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('滚动布局'),
      ),
      body: new ListView(
        children: <Widget>[
          new Center(
            child: new Text(
              '\n大标题',
              style: new TextStyle(fontFamily: 'serif', fontSize: 20.0),
            ),
          ),
          new Center(
            child: new Text(
              '小标题',
              style: new TextStyle(
                fontFamily: 'serif',
                fontSize: 12.0,
              ),
            ),
          ),
          new Center(
            child: new Text(
              '''
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
             内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is 
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is 
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
             内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
             内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
             内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
            内容sadfManual valve defensive play Fly fost happen happen is
           
                             ''',
              style: new TextStyle(fontSize: 14.0),
            ),
          )
        ],
      ),
    );
  }
}

5.Align:

AlignThe alignment control,Can the child controls the way according to the specified alignment,And according to the size of the child controls to adjust their size.AlignAlignment of child controls means has the following several kinds of

bottomCenter    (0.5, 1.0)    底部中心
bottomLeft    (0.0, 1.0)    左下角
bottomRight    (1.0, 1.0)    右下角
center    (0.5, 0.5)    水平垂直居中
centerLeft    (0.0, 0.5)    Left edge center
centerRight    (1.0, 0.5)    Right edge center
topCenter    (0.5, 0.0)    顶部中心
topLeft    (0.0, 0.0)    左上角
topRight    (1.0, 0.0)    右上角

来简单使用一下:

代码:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new AlignLayoutDemo()));
}
class AlignLayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Align布局'),
      ),
      body: new Stack(
        children: <Widget>[
          new Align(
            alignment: new FractionalOffset(0.0, 0.5),
            child: new Text(
              'I'm in the center of the left edge',
              style: new TextStyle(fontSize: 35.0),
            ),
          ),
          new Align(
            alignment: new FractionalOffset(1.0, 1.0),
            child: new Text(
              '我在右下角',
              style: new TextStyle(fontSize: 30.0),
            ),
          )
        ],
      ),
    );
  }
}

6.SizedBox

SizedBoxTo enforce control child controls wide high display,For example, I specified a wide high for200的SiezedBox布局,其里面的child widgetThe wide high also is limited dead biggest wide high asSizedBox的宽高,Even if he has more wide high.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new SizedBoxLayoutDemo()));
}
class SizedBoxLayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('SizedBox布局'),
      ),
      body: new SizedBox(
        width: 200.0,
        height: 200.0,
        child: new Container(
          decoration: new BoxDecoration(color: Colors.red),
        ),
      ),
    );
  }
}

利用SizedBox限定Container的宽高为200:

 

7.Opacity

OpacityThe control can adjust the opacity of child controls,Make the child controls part of the transparent,The quantity of opacity from0.0到1.1之间,0.0表示完全透明,1.1表示完全不透明.

如图:我在StackLayoutPlace two childwidget,其中Text在Stack下方,I put the upperOpacityThe layout of the transparency is set to the0.5,We can faintly see belowText显示的内容,The reader can put the opacity value test results.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new OpacityLayoutDemo()));
}

//OpacityThe control can adjust the opacity of child controls,Make the child controls part of the transparent,The quantity of opacity from0.0到1.1之间,0.0表示完全透明,1.1表示完全不透明.
class OpacityLayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      appBar: new AppBar(
        title: new Text('Opacity'),
      ),
      body: new Center(
        child: new Stack(
          alignment: AlignmentDirectional.center,
          children: <Widget>[
            new Text("I'm in a transparent area below"),
            new Opacity(
              opacity: 0.5,
              child: new Container(
                width: 200.0,
                height: 220.0,
                decoration: new BoxDecoration(color: Colors.redAccent),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

 

本篇内容有点多,Aims to bring together summary masterFlutterSeveral kinds of layout are,In addition several layout in reality development usage scenario is less,There is no one by one on analysis, 读者感兴趣的话,To refer to the official documentation try specific usage.

下一篇:Flutter入门进阶之旅(七)GestureDetector

原网站

版权声明
本文为[Xie Dong_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091203557018.html