Menu
CoddyTech

最大宽度

本课属于 Coddy Flutter 学习旅程的“适配不同屏幕的布局”单元。第 15 课,共 30 课。

带有较长文本的卡片会一直变宽,直到铺满整个屏幕。在手机上看起来没问题;在平板上,同一张卡片会延伸成一行长达一千像素的文本,很难阅读。

ConstrainedBox 会限制其子项的大小。maxWidth: 表示它最多可以扩展到多宽:

ConstrainedBox(
  constraints: const BoxConstraints(maxWidth: 400),
  child: Container(...),
)

在宽度小于 400 像素的屏幕上,卡片仍会缩小以适应屏幕。在更宽的屏幕上,它会停在 400 像素,文本也会换成更多行。

BoxConstraints 还接受 minWidth:、minHeight: 和 maxHeight:。最小值表示子项至少要有多大,因此它不会阻止子项继续变大。

challenge icon

挑战

简单

在宽屏上保持引言卡片易于阅读:让它的宽度最多扩展到 320 像素。

亲手试试

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(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Quote of the Day')),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Center(
            child: Container(
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Colors.amber.shade100,
                borderRadius: BorderRadius.circular(16),
              ),
              child: const Text(
                'The best way to learn to build apps is to build apps, one small screen at a time.',
                style: TextStyle(fontSize: 20),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

适配不同屏幕的布局中的所有课

自己练习: Flutter 在线编译器