Menu
CoddyTech

在容器内使用 Align 对齐

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

Center 会把子组件放在可用空间的中间。Align 也能做到这一点,还可以把子组件放在你选择的位置:

Container(
  height: 200,
  color: Colors.teal,
  child: const Align(
    alignment: Alignment.topRight,
    child: Text('Top right'),
  ),
)

这些位置以角和边命名:Alignment.topLeft、topCenter、topRight、centerLeft、center、centerRight、bottomLeft、bottomCenter 和 bottomRight。Center 就是使用 Alignment.center 的 Align。

Stack 也接受 alignment:,它会设置所有非 Positioned 子组件的位置:Stack(alignment: Alignment.bottomCenter, children: [...])。

challenge icon

挑战

简单

将 Mountains 标题从封面的中间移到左下角。内边距会让它与两侧边缘都相距 16 像素。

亲手试试

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('Travel')),
        body: Column(
          children: [
            Container(
              height: 240,
              color: Colors.indigo,
              child: const Center(
                child: Padding(
                  padding: EdgeInsets.all(16),
                  child: Text(
                    'Mountains',
                    style: TextStyle(fontSize: 28, color: Colors.white),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
quiz icon自我测试

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

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

自己练习: Flutter 在线编译器