返回

Flutter开发日记——Flutter布局Widget详解(下)

前端

前言

在上一篇文章中,我们已经介绍了一些常用的布局Widget,包括Row、Column、Flex和Wrap。在本文中,我们将继续探讨一些常用的布局Widget,包括Stack、IndexedStack、GridView和CustomScrollView等。

Stack

Stack控件允许您将多个子控件堆叠在一起,并指定每个子控件的相对位置。您可以使用Stack控件来创建复杂的布局,例如带有浮动按钮的列表或带有轮播图的页面。

以下是Stack控件的示例代码:

Stack(
  children: [
    Container(
      color: Colors.blue,
      width: 200,
      height: 200,
    ),
    Positioned(
      top: 100,
      left: 100,
      child: Container(
        color: Colors.red,
        width: 100,
        height: 100,
      ),
    ),
  ],
)

IndexedStack

IndexedStack控件与Stack控件类似,但它允许您指定当前显示的子控件。您可以使用IndexedStack控件来创建页面切换器或选项卡栏。

以下是IndexedStack控件的示例代码:

IndexedStack(
  index: 0,
  children: [
    Container(
      color: Colors.blue,
      width: 200,
      height: 200,
    ),
    Container(
      color: Colors.red,
      width: 200,
      height: 200,
    ),
  ],
)

GridView

GridView控件允许您将子控件排列成网格。您可以使用GridView控件来创建图片库、产品列表或联系人列表。

以下是GridView控件的示例代码:

GridView.count(
  crossAxisCount: 2,
  children: [
    Container(
      color: Colors.blue,
      width: 100,
      height: 100,
    ),
    Container(
      color: Colors.red,
      width: 100,
      height: 100,
    ),
    Container(
      color: Colors.green,
      width: 100,
      height: 100,
    ),
  ],
)

CustomScrollView

CustomScrollView控件允许您创建自定义的滚动视图。您可以使用CustomScrollView控件来创建带有头部和尾部的列表、带有分页的列表或带有无限滚动的列表。

以下是CustomScrollView控件的示例代码:

CustomScrollView(
  slivers: [
    SliverAppBar(
      title: Text('Flutter布局Widget详解(下)'),
    ),
    SliverList(
      delegate: SliverChildListDelegate(
        [
          Container(
            color: Colors.blue,
            width: 200,
            height: 200,
          ),
          Container(
            color: Colors.red,
            width: 200,
            height: 200,
          ),
          Container(
            color: Colors.green,
            width: 200,
            height: 200,
          ),
        ],
      ),
    ),
  ],
)