🔖 หมวดบทเรียน: การออกแบบ UI ที่รองรับหลายขนาดหน้าจอ (มือถือ-แท็บเล็ต-เว็บ)
📌 เหมาะสำหรับ: นักพัฒนาที่ต้องการให้แอปใช้งานได้ดีทั้งมือถือและแท็บเล็ต หรือแม้แต่บนเว็บ
🎯 เป้าหมาย: สร้าง UI ที่ปรับเปลี่ยนขนาดและโครงสร้างอัตโนมัติตามอุปกรณ์ผู้ใช้
🧭 เกริ่นนำ
Responsive Layout เป็นหัวใจสำคัญของแอปที่ต้องรองรับหลายอุปกรณ์ Flutter มีเครื่องมือที่ช่วยให้เราทำได้ง่าย เช่น MediaQuery
, LayoutBuilder
, และการแบ่ง Breakpoint เอง ในบทนี้เราจะสร้าง Layout ที่ปรับโครงสร้างอัตโนมัติตามความกว้างหน้าจอ
📐 MediaQuery เบื้องต้น
final width = MediaQuery.of(context).size.width;
final isTablet = width > 600;
🧱 LayoutBuilder + Responsive Widget
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > 800) {
return WebLayout();
} else if (constraints.maxWidth > 600) {
return TabletLayout();
} else {
return MobileLayout();
}
},
);
}
🧰 Adaptive UI ด้วย Widget เฉพาะ platform
if (Platform.isIOS) {
return CupertinoButton(...);
} else {
return ElevatedButton(...);
}
✅ เทคนิคเพิ่มเติม
- ใช้
FractionallySizedBox
และFlexible
ช่วยจัดสัดส่วน - สร้าง
ResponsiveWrapper
แยก reusable layout - ใช้
flutter_screenutil
หรือresponsive_framework
ช่วยได้
✅ สรุป
- UI ควรรองรับหน้าจอหลายขนาดตั้งแต่แรก
- ใช้
MediaQuery
,LayoutBuilder
, และ breakpoints - สร้างแยก Layout ตาม platform ถ้าจำเป็น (iOS/Android/Web)
บทถัดไปเราจะเรียนรู้ การจัดการ Animation และ Transition ขั้นสูง เพื่อยกระดับประสบการณ์ผู้ใช้ให้ดียิ่งขึ้น