MST
星途 面试题库

面试题:Flutter中Flex布局在自适应场景下的深度应用

在Flutter项目中,要求实现一个复杂的自适应布局,屏幕分为上、中、下三个部分,上部是固定高度的标题栏,中部根据剩余空间按比例分配为左右两个区域,其中左区域又分为上下两个子区域且高度可自适应内容,右区域高度自适应内容,下部是一个固定高度的底部栏。请详细描述使用Flex布局及其相关属性(如Flex、Expanded、Flexible等)来实现该布局的思路,并给出关键代码片段。
15.6万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 整体布局:使用 Column 作为整体布局容器,将屏幕分为上、中、下三个部分。
  2. 上部标题栏:使用普通的 Container 或者 AppBar 来实现固定高度的标题栏,设置其 height 属性。
  3. 中部区域:在 Column 的中间部分使用 Row 来划分左右两个区域。左区域使用 Column 进一步划分为上下两个子区域,高度自适应内容;右区域直接使用 Expanded 包裹内容以自适应高度。通过 Expanded 按比例分配剩余空间,可设置不同的 flex 值来调整左右区域比例。
  4. 下部底部栏:同样使用普通的 Container 设置固定高度作为底部栏。

关键代码片段

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            // 上部标题栏
            Container(
              height: 50,
              color: Colors.blue,
              child: Center(
                child: Text('标题栏'),
              ),
            ),
            // 中部区域
            Expanded(
              child: Row(
                children: <Widget>[
                  // 左区域
                  Expanded(
                    flex: 2, // 可调整比例
                    child: Column(
                      children: <Widget>[
                        Expanded(
                          child: Container(
                            color: Colors.green,
                            child: Center(
                              child: Text('左区域上部子区域'),
                            ),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            color: Colors.lightGreen,
                            child: Center(
                              child: Text('左区域下部子区域'),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  // 右区域
                  Expanded(
                    flex: 3, // 可调整比例
                    child: Container(
                      color: Colors.red,
                      child: Center(
                        child: Text('右区域'),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 下部底部栏
            Container(
              height: 50,
              color: Colors.yellow,
              child: Center(
                child: Text('底部栏'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}