百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

flutter软件开发笔记08-容器使用方法

wptr33 2025-04-26 21:38 15 浏览

在 Flutter 3 中,容器组件是用于布局、装饰或约束子组件的核心部件,能让程序更加美观,如何学习呢,能快速的应用起来,下面通过例子,来快速理解各种容器组件的使用方法。

一程序界面

二 代码实现

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 容器组件示例',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const ContainerDemoScreen(),
    );
  }
}

class ContainerDemoScreen extends StatelessWidget {
  const ContainerDemoScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('容器组件示例')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            // 1. Container 示例
            _buildContainerDemo(),
            const SizedBox(height: 20),

            // 2. Row/Column 示例
            _buildRowColumnDemo(),
            const SizedBox(height: 20),

            // 3. Stack 示例
            _buildStackDemo(),
            const SizedBox(height: 20),

            // 4. ListView/GridView 示例
            _buildListAndGridDemo(),
            const SizedBox(height: 20),

            // 5. Expanded/Flexible 示例
            _buildExpandedDemo(),
            const SizedBox(height: 20),

            // 6. Card 示例
            _buildCardDemo(),
          ],
        ),
      ),
    );
  }

  // ---------- 以下是各个容器的构建方法 ----------

  // 1. Container 示例
  Widget _buildContainerDemo() {
    return Container(
      width: 200,
      height: 100,
      margin: const EdgeInsets.all(10),
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.blue[100],
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: Colors.blue, width: 2),
      ),
      child: const Center(
        child: Text('Container', style: TextStyle(color: Colors.blue)),
      ),
    );
  }

  // 2. Row/Column 示例
  Widget _buildRowColumnDemo() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Container(width: 50, height: 50, color: Colors.red),
            Container(width: 50, height: 50, color: Colors.green),
            Container(width: 50, height: 50, color: Colors.blue),
          ],
        ),
        const SizedBox(height: 10),
        Column(
          children: const [
            Text('Row 水平排列'),
            Text('Column 垂直排列'),
          ],
        ),
      ],
    );
  }

  // 3. Stack 示例
  Widget _buildStackDemo() {
    return SizedBox(
      width: 200,
      height: 100,
      child: Stack(
        children: [
          Container(color: Colors.yellow[100]),
          Positioned(
            top: 10,
            left: 10,
            child: Container(width: 40, height: 40, color: Colors.red),
          ),
          const Positioned(
            bottom: 10,
            right: 10,
            child: Text('Stack 层叠'),
          ),
        ],
      ),
    );
  }

  // 4. ListView/GridView 示例
  Widget _buildListAndGridDemo() {
    return Column(
      children: [
        SizedBox(
          height: 100,
          child: ListView(
            scrollDirection: Axis.horizontal,
            children: List.generate(
              5,
              (index) => Container(
                width: 80,
                margin: const EdgeInsets.all(5),
                color: Colors.orange[100],
                child: Center(child: Text('Item $index')),
              ),
            ),
          ),
        ),
        const SizedBox(height: 10),
        GridView.count(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          crossAxisCount: 3,
          children: List.generate(
            6,
            (index) => Container(
              margin: const EdgeInsets.all(2),
              color: Colors.purple[100],
              child: Center(child: Text('Grid $index')),
            ),
          ),
        ),
      ],
    );
  }

  // 5. Expanded/Flexible 示例
  Widget _buildExpandedDemo() {
    return Container(
      height: 80,
      color: Colors.grey[200],
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Container(color: Colors.red, child: const Center(child: Text('Expanded'))),
          ),
          Flexible(
            flex: 1,
            child: Container(color: Colors.blue, child: const Center(child: Text('Flexible'))),
          ),
        ],
      ),
    );
  }

  // 6. Card 示例
  Widget _buildCardDemo() {
    return Card(
      elevation: 5,
      color: Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: const [
            Icon(Icons.star, color: Colors.amber, size: 40),
            SizedBox(height: 10),
            Text('Card 组件示例', style: TextStyle(fontWeight: FontWeight.bold)),
            Text('带阴影的卡片式布局'),
          ],
        ),
      ),
    );
  }
}

三 代码讲解

运行效果

这个示例会展示以下内容:

  1. 蓝色圆角 Container
  2. 红绿蓝方块水平排列的 Row
  3. 黄色背景叠加红色方块和文字的 Stack
  4. 水平滚动 ListView 和 3列 GridView
  5. 红蓝比例分割的 Expanded/Flexible
  6. 带阴影的 Card 卡片

核心容器组件讲解

1. Container

  • 用途:全能布局容器,可设置尺寸、边距、颜色等。
  • 关键属性
  • margin // 外边距 padding // 内边距 decoration // 装饰(颜色、边框、圆角等)

2. Row 与 Column

  • 用途:水平/垂直排列子组件。
  • 关键属性
  • mainAxisAlignment // 主轴对齐方式(如居中、两端对齐) crossAxisAlignment // 交叉轴对齐方式

3. Stack

  • 用途:层叠布局,结合 Positioned 控制子组件位置。
  • 典型场景:图标+文字叠加、浮动按钮。

4. ListView 与 GridView

  • 用途:滚动列表和网格布局。
  • 注意
  • shrinkWrap: true // 当嵌套在其他滚动组件中时需要设置 scrollDirection // 滚动方向(水平/垂直)

5. Expanded 与 Flexible

  • 用途:在 Row/Column 中按比例分配剩余空间。
  • 区别:Expanded 必须填满剩余空间Flexible 可以自适应内容大小

6. Card

  • 用途:带阴影的卡片式设计。
  • 关键属性
  • elevation // 阴影强度 shape // 自定义形状(如圆角半径)

如何调试?

  1. 复制代码到 lib/main.dart
  2. 运行 flutter run
  3. 尝试修改以下参数观察变化:修改 Container 的 margin 和 padding调整 Row 的 mainAxisAlignment改变 Expanded 的 flex 比例

通过这个示例,你可以直观理解 Flutter 容器组件如何协作构建复杂界面。如果需要更高级的布局,可以学习 LayoutBuilder 或 CustomScrollView。

相关推荐

redis的八种使用场景

前言:redis是我们工作开发中,经常要打交道的,下面对redis的使用场景做总结介绍也是对redis举报的功能做梳理。缓存Redis最常见的用途是作为缓存,用于加速应用程序的响应速度。...

基于Redis的3种分布式ID生成策略

在分布式系统设计中,全局唯一ID是一个基础而关键的组件。随着业务规模扩大和系统架构向微服务演进,传统的单机自增ID已无法满足需求。高并发、高可用的分布式ID生成方案成为构建可靠分布式系统的必要条件。R...

基于OpenWrt系统路由器的模式切换与网页设计

摘要:目前商用WiFi路由器已应用到多个领域,商家通过给用户提供一个稳定免费WiFi热点达到吸引客户、提升服务的目标。传统路由器自带的Luci界面提供了工厂模式的Web界面,用户可通过该界面配置路...

这篇文章教你看明白 nginx-ingress 控制器

主机nginx一般nginx做主机反向代理(网关)有以下配置...

如何用redis实现注册中心

一句话总结使用Redis实现注册中心:服务注册...

爱可可老师24小时热门分享(2020.5.10)

No1.看自己以前写的代码是种什么体验?No2.DooM-chip!国外网友SylvainLefebvre自制的无CPU、无操作码、无指令计数器...No3.我认为CS学位可以更好,如...

Apportable:拯救程序员,IOS一秒变安卓

摘要:还在为了跨平台使用cocos2d-x吗,拯救objc程序员的奇葩来了,ApportableSDK:FreeAndroidsupportforcocos2d-iPhone。App...

JAVA实现超买超卖方案汇总,那个最适合你,一篇文章彻底讲透

以下是几种Java实现超买超卖问题的核心解决方案及代码示例,针对高并发场景下的库存扣减问题:方案一:Redis原子操作+Lua脚本(推荐)//使用Redis+Lua保证原子性publicbo...

3月26日更新 快速施法自动施法可独立设置

2016年3月26日DOTA2有一个79.6MB的更新主要是针对自动施法和快速施法的调整本来内容不多不少朋友都有自动施法和快速施法的困扰英文更新日志一些视觉BUG修复就不翻译了主要翻译自动施...

Redis 是如何提供服务的

在刚刚接触Redis的时候,最想要知道的是一个’setnameJhon’命令到达Redis服务器的时候,它是如何返回’OK’的?里面命令处理的流程如何,具体细节怎么样?你一定有问过自己...

lua _G、_VERSION使用

到这里我们已经把lua基础库中的函数介绍完了,除了函数外基础库中还有两个常量,一个是_G,另一个是_VERSION。_G是基础库本身,指向自己,这个变量很有意思,可以无限引用自己,最后得到的还是自己,...

China's top diplomat to chair third China-Pacific Island countries foreign ministers' meeting

BEIJING,May21(Xinhua)--ChineseForeignMinisterWangYi,alsoamemberofthePoliticalBureau...

移动工作交流工具Lua推出Insights数据分析产品

Lua是一个适用于各种职业人士的移动交流平台,它在今天推出了一项叫做Insights的全新功能。Insights是一个数据平台,客户可以在上面实时看到员工之间的交流情况,并分析这些情况对公司发展的影响...

Redis 7新武器:用Redis Stack实现向量搜索的极限压测

当传统关系型数据库还在为向量相似度搜索的性能挣扎时,Redis7的RedisStack...

Nginx/OpenResty详解,Nginx Lua编程,重定向与内部子请求

重定向与内部子请求Nginx的rewrite指令不仅可以在Nginx内部的server、location之间进行跳转,还可以进行外部链接的重定向。通过ngx_lua模块的Lua函数除了能实现Nginx...