MST

星途 面试题库

面试题:Flutter中如何通过布局实现基本的响应式UI

在Flutter中,假设要实现一个简单页面,在大屏设备上展示三列等宽卡片,在小屏设备上依次竖向排列卡片。请描述使用哪些Widget以及布局思路来完成这个响应式UI。
11.9万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试
  1. 布局思路
    • 利用LayoutBuilder来获取当前设备的屏幕尺寸信息。
    • 根据屏幕宽度判断是大屏还是小屏设备,然后采用不同的布局方式。
  2. 使用的Widget
    • LayoutBuilder:用于获取父级的约束,从而得到屏幕尺寸信息。例如:
LayoutBuilder(
  builder: (BuildContext context, BoxConstraints constraints) {
    // 根据constraints.maxWidth判断屏幕大小
    return _buildLayout(constraints.maxWidth);
  },
)
  • Row:在大屏设备上用于水平排列卡片,实现三列布局。例如:
Row(
  children: [
    _buildCard(),
    _buildCard(),
    _buildCard(),
  ],
)
  • Column:在小屏设备上用于竖向排列卡片。例如:
Column(
  children: [
    _buildCard(),
    _buildCard(),
    _buildCard(),
  ],
)
  • 自定义卡片Widget:假设为_buildCard,用于构建单个卡片。例如:
Widget _buildCard() {
  return Card(
    child: Container(
      width: 200,
      height: 200,
      child: Center(
        child: Text('Card'),
      ),
    ),
  );
}
  • Expanded:在Row布局中,用于使卡片等宽。例如在大屏布局的Row中:
Row(
  children: [
    Expanded(child: _buildCard()),
    Expanded(child: _buildCard()),
    Expanded(child: _buildCard()),
  ],
)
  1. 完整代码示例
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Responsive UI'),
        ),
        body: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            return _buildLayout(constraints.maxWidth);
          },
        ),
      ),
    );
  }

  Widget _buildLayout(double screenWidth) {
    if (screenWidth >= 600) {
      // 大屏设备,三列布局
      return Row(
        children: [
          Expanded(child: _buildCard()),
          Expanded(child: _buildCard()),
          Expanded(child: _buildCard()),
        ],
      );
    } else {
      // 小屏设备,竖向排列
      return Column(
        children: [
          _buildCard(),
          _buildCard(),
          _buildCard(),
        ],
      );
    }
  }

  Widget _buildCard() {
    return Card(
      child: Container(
        width: 200,
        height: 200,
        child: Center(
          child: Text('Card'),
        ),
      ),
    );
  }
}