Flutter(二) Building Layouts in Flutter tutorial

这部分是 Flutter 官网中 Learn More 模块中的布局课程。布局在Flutter应用中作用很大,学习时间2天。

结构

首先通过一个例子介绍了整体的布局,直观。
后面介绍一些布局原理和细节。

例子

Flutter中引入了一个新的概念,叫做widget,这里面包含了可视化的UI和布局模型。

整体结构

单个结构分析

整体展示

Widget 布局详解

Flutter 布局方法

  1. Widgets 是UI元素
  2. Widgets 是布局元素
  3. 通过简单的 Widgets 组成复杂的 Widgets

Widgets 是布局核心部分。在 Flutter中,几乎所有的东西都是 widget,甚至布局模型也是。图片,图标,文本所有能看到的东西都是widgets。但是有些你看不到的依然是widget,比如行,列以及格子。

布局一个 widget

  1. app 本身就是widget
  2. 创建添加以及布局一个widget很简单
  3. 将布局widget添加到app的widget上,就会显示到设备上
  4. Scaffold,是 Material 组件库中的一个widget,有一些默认的设置可供使用
  5. 我们可以通过是使用标准的widgets创建app

这一部分主要是创建并添加一个简单的 widget,包括创建一个简单的app。

在flutter中,只需要简单几步就可以将文本,icon还有图片显示到屏幕上:

  1. 选择一种你想是使用的 widget(这里使用Center,更多布局组件
  2. 创建一个包含可显示内容的widget
1
2
3
4
5
6
// 文本 widget
new Text('Hello world', style: new TextStyle(fontSize:32.0))
// 图片 widget,这里涉及到向工程中添加图片资源
new Image.asset('images/myPic.jpg', fit: BoxFit.cover)
// 图标 widget
new Icon(Icons.star, color: Color.ret[500])
  1. 将可视化的widget添加到布局widget上
    所有的布局widget,都有 child 属性,或者是 children 属性,这取决于你要向布局widget中添加怎样的 widget。

    1
    2
    new Center (
    child: new Text('Hello world, style:new TextStyle(fontSize:f 32.0))
  2. 将 布局 widget 添加到页面上

标准 widgets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

import 'package:flutter/material.dart';

void main() {
runApp(new MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(color: Colors.white),
child: new Center(
child: new Text('Hello World',
style: new TextStyle(fontSize: 40.0, color: Colors.black87)),
),
);
}
}

material widget

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(color: Colors.white),
child: new Center(
child: new Text('Hello world',
style: new TextStyle(fontSize: 40.0, color: Colors.black87),
textDirection: TextDirection.ltr,),

),
);
}
}

从竖直和水平两个方向布局多个widgets

最常用的一种布局模式是根据竖直和水平方向排列widgets。使用 Row widget 排列水平方向,使用 Column布局竖直方向。

  1. Row 和 Column 是最常见的布局模式;
  2. 行和列可以通过 child 属性交叉排列;
  3. 一个 child widget 可以是 Row ,Column 或者其他的复杂 widget
  4. Row 和 Column 可以定义自己的方向和子widget
  5. 可以拉伸或者约束某个widget
  6. 没看懂这句 ‘You can specify how child widgets use the Row’s or Column’s available space.’

内容

——————————————————————参考文章—————————————————————–

  1. Building Layouts in Flutter
  2. 为什么说Flutter是革命性的?)
-------------本文结束谢谢欣赏-------------
Alice wechat