【Flutter -- 布局】Container 的基础使用

在这里插入图片描述

一、简介

Container 在 Flutter 中太常见了。官方给出的简介,是一个结合了绘制(painting)、定位(positioning)以及尺寸(sizingwidgetwidget

可以得出几个信息,它是一个组合的 widget,内部有绘制 widget、定位 widget、尺寸 widget。后续看到的不少 widget ,都是通过一些更基础的 widget 组合而成的。

1. 作用

用来放置 widget 的容器,有 paddingmargin、位置、大小等参数

  • 最常用的默认布局!只能包含一个 child:,支持配置 padding,margin,color,宽高,decoration(一般配置边框和阴影)等配置,
  • 在 Flutter 中,不是所有的控件都有 宽高、padding、margin、color 等属性,所以有 Padding、CenterWidget

2. 属性

  • keyContainer 唯一标识符,用于查找更新。

  • alignment:控制child的对齐方式,如果container或者container父节点尺寸大于child的尺寸,这个属性设置会起作用,有很多种对齐方式。

  • paddingdecoration内部的空白区域,如果有child的话,child位于padding内部。paddingmargin的不同之处在于,padding是包含在content内,而margin则是外部边界,设置点击事件的话,padding区域会响应,而margin区域不会响应。

  • color:用来设置container背景色,如果foregroundDecoration设置的话,可能会遮盖color效果。

  • decoration:绘制在child后面的装饰,设置了decoration的话,就不能设置color属性,否则会报错,此时应该在decoration中进行颜色的设置。

  • foregroundDecoration:绘制在child前面的装饰。

  • widthcontainer的宽度,设置为double.infinity可以强制在宽度上撑满,不设置,则根据child和父节点两者一起布局。

  • heightcontainer的高度,设置为double.infinity可以强制在高度上撑满。

  • constraints:添加到child上额外的约束条件。

  • margin:围绕在decorationchild之外的空白区域,不属于内容区域。

  • transform:设置container的变换矩阵,类型为Matrix4

  • childcontainer中的内容widget

3. 使用场景

Container 算是目前项目中,最经常用到的一个 widget 。在实际使用过程中,在以下情况会使用到 Container,当然并不是绝对的,也可以通过其他 widget 来实现。

  • 需要设置间隔(这种情况下,如果只是单纯的间隔,也可以通过Padding来实现);
  • 需要设置背景色;
  • 需要设置圆角或者边框的时候(ClipRRect也可以实现圆角效果);
  • 需要对齐(Align也可以实现);
  • 需要设置背景图片的时候(也可以使用Stack实现)。

二、实例

1. 效果图

在这里插入图片描述

2. 代码

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(
      title: 'Welcome to Flutter',

      home: Scaffold(
          appBar: AppBar(
            title: Text('Container 的基本使用'),
          ),
          body: Container (
            constraints: BoxConstraints.expand(
              height: Theme.of(context).textTheme.headline4!.fontSize! * 1.1 + 200,
            ),
            decoration: BoxDecoration(
              border: Border.all(width: 2.0,color: Colors.red),
              color: Colors.grey,
              borderRadius: BorderRadius.all(Radius.circular(20.0)),
              image: DecorationImage(
                image: AssetImage("images/avatar.png"),
                centerSlice: Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0)
              ),
            ),
            padding: EdgeInsets.all(8.0),
            alignment: Alignment.center,
            child: Text('Hello Kevin',
            style: Theme.of(context).textTheme.displayMedium!.copyWith(color: Colors.black)),
            transform: Matrix4.rotationZ(0.3),

          )
      )

    );
  }
}

猜你喜欢

转载自blog.csdn.net/duoduo_11011/article/details/125864989