使用 Positioned 定位到角落
本课属于 Coddy Flutter 学习旅程的“适配不同屏幕的布局”单元。第 11 课,共 30 课。
Stack 的子组件从它的左上角开始。要把子组件放到其他位置,可以用 Positioned 包裹它,并指定它距离边缘有多远:
Stack(
children: [
Container(height: 200, color: Colors.grey),
const Positioned(
bottom: 8,
left: 8,
child: Text('Bottom left'),
),
],
)top:、bottom:、left: 和 right: 表示距离 Stack 相应边缘的像素数。每个方向各指定一侧:top 或 bottom,以及 left 或 right。
Positioned 子组件不会改变 Stack 的大小。它的大小仍由照片决定。
挑战
简单将 SALE 徽章移到照片的右上角,距离顶部 12 像素,距离右侧 12 像素。
亲手试试
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('Shop')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Stack(
children: [
Container(
height: 200,
color: Colors.blueGrey.shade100,
child: const Center(child: Icon(Icons.image, size: 64)),
),
Container(
padding: const EdgeInsets.all(8),
color: Colors.red,
child: const Text('SALE', style: TextStyle(color: Colors.white)),
),
],
),
const SizedBox(height: 12),
const Text('Running shoes', style: TextStyle(fontSize: 20)),
],
),
),
),
);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
适配不同屏幕的布局中的所有课
自己练习: Flutter 在线编译器