當 Positioned
的座標為 負值
時,常會搭配 clipBehavior: Clip.none
讓 Widget 顯示在 Container
之上。
Version
Flutter 3.24.5
Flutter
- Android 與 iOS 都成功使用
Position
與ClipBehavior
實現以座標定位
Positioned
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
const Home({super.key});
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('Positioned with Negative Values'),
);
var baseContainer = Container(
width: 300,
height: 300,
color: Colors.blue[100],
);
var topRight = Positioned(
top: -20,
right: -20,
child: Container(
width: 100,
height: 100,
color: Colors.red,
child: const Center(
child: Text(
'Top Right',
style: TextStyle(
color: Colors.white,
),
),
),
),
);
var body = Center(
child: Stack(
clipBehavior: Clip.none,
children: [
baseContainer,
topRight,
],
),
);
return MaterialApp(
home: Scaffold(
appBar: appBar,
body: body,
),
);
}
}
Line 36
var body = Center(
child: Stack(
clipBehavior: Clip.none,
children: [
baseContainer,
topRight,
],
),
);
Stack
:當要使用Positioned
時,本身與欲參考 widget 都要放在Stack
內clipBehavior: clip.none
:當 Positioned 的座標使用負值
時,會被所參考的 Container 所 clip 掉,必須加上clipBehavior: Clip.none
避免被 clip
Line 30
var baseContainer = Container(
width: 300,
height: 300,
color: Colors.blue[100],
);
baseContainer
:被Positioned
所參考座標的 widget
Line 18
var topRight = Positioned(
top: -20,
right: -20,
child: Container(
width: 100,
height: 100,
color: Colors.red,
child: const Center(
child: Text(
'Top Right',
style: TextStyle(
color: Colors.white,
),
),
),
),
);
Positioned
:將 widget 包在Positioned
內,以top
、right
指定座標top
:指定負值
right
:指定負值
Conclusion
Positioned
必須搭配Stack
使用- 當座標為
負值
時,必須搭配clipBehavior: Clip.none
才不會被所參考的Container
給 clip 掉