Dev to webs {Coding…}

ร บทเรียนฟรีด้านการพัฒนาซอฟต์แวร์ ที่ครอบคลุมเนื้อหาหลากหลาย ตั้งแต่การเขียนโค้ดพื้นฐานไปจนถึงเทคนิคขั้นสูง

บทที่ 7: การใส่ปุ่มและการจัดการการคลิก (Button, GestureDetector)

🔖 หมวดบทเรียน: การโต้ตอบกับผู้ใช้ผ่านปุ่มและ gesture

📌 เหมาะสำหรับ: ผู้เริ่มต้นที่ต้องการให้แอปตอบสนองต่อการกดและสัมผัส

🎯 เป้าหมาย: เรียนรู้การใช้ Button และ GestureDetector ในการรับอินพุตจากผู้ใช้

🧭 เกริ่นนำ

แอปพลิเคชันส่วนใหญ่ต้องมีการโต้ตอบกับผู้ใช้ เช่น การกดปุ่ม เพื่อสั่งให้แอปทำอะไรบางอย่าง ใน Flutter มี widget สำหรับจัดการกับการคลิกหรือสัมผัสหลากหลายรูปแบบ เช่น ElevatedButton, TextButton, IconButton และ GestureDetector ที่สามารถตรวจจับการแตะ ลาก ดับเบิลคลิก ได้หลากหลายรูปแบบ

🔘 ElevatedButton

ElevatedButton(
  onPressed: () {
    print("คุณกดปุ่มแล้ว!");
  },
  child: Text("กดฉัน")
)

  • onPressed คือสิ่งที่จะเกิดขึ้นเมื่อกด
  • child คือ widget ที่แสดงบนปุ่ม

🧵 TextButton และ IconButton

TextButton(
  onPressed: () {},
  child: Text("ข้อความ")
)

IconButton(
  icon: Icon(Icons.thumb_up),
  onPressed: () {
    print("Like!");
  },
)

✋ GestureDetector

ใช้ตรวจจับ gesture นอกเหนือจากการกด เช่น แตะค้าง ดับเบิลแตะ

GestureDetector(
  onTap: () {
    print("แตะหน้าจอ");
  },
  child: Container(
    color: Colors.amber,
    padding: EdgeInsets.all(20),
    child: Text("แตะตรงนี้"),
  ),
)

🧪 ตัวอย่างรวม

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("ปุ่มและ Gesture")),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  print("กดปุ่ม Elevated");
                },
                child: Text("Elevated")
              ),
              SizedBox(height: 10),
              IconButton(
                icon: Icon(Icons.favorite),
                color: Colors.pink,
                onPressed: () {
                  print("ชอบ!");
                },
              ),
              SizedBox(height: 10),
              GestureDetector(
                onDoubleTap: () {
                  print("ดับเบิลคลิก!");
                },
                child: Container(
                  padding: EdgeInsets.all(20),
                  color: Colors.lightGreen,
                  child: Text("ดับเบิลแตะตรงนี้"),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

✅ สรุป

  • ใช้ ElevatedButton, TextButton, และ IconButton เพื่อรับคำสั่งจากผู้ใช้
  • ใช้ GestureDetector เมื่อคุณต้องการควบคุม gesture ที่ซับซ้อนขึ้น เช่น แตะค้าง ดับเบิลแตะ
  • การตอบสนองต่อผู้ใช้เป็นหัวใจสำคัญของแอปทุกประเภท

บทถัดไปเราจะเรียนรู้การจัดการ State และการใช้ StatefulWidget เพื่อจัดการค่าที่เปลี่ยนแปลงได้