Devdit
 

Flutter ดึงค่าจาก TextField มาแสดงที่ Text

657

Flutter ดึงค่าจาก TextField มาแสดงที่ Text บทความนี้สอนเขียนโปรแกรมเมื่อผู้ใช้งานกรอกข้อมูลลงใน TextField จะดึงข้อมูลดังกล่าวมาแสดงที่ Text ด้วยข้อความ สวัสดี ตามด้วยค่าที่อยู่ใน TextField สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง Flutter ดึงค่าจาก TextField มาแสดงที่ Text

1. นำเข้าไฟล์ flutter/material.dart ด้วยคำสั่ง import และรัน class MyApp เป็นหน้าจอแรกด้วยคำสั่ง runApp

import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    home: MyApp(),
  ));
}

 

2. สร้าง class แบบ StatefulWidget ชื่อ MyApp โดยมีการสร้างตัวแปรชื่อ name เมื่อผู้ใช้งานกรอกข้อมูลลงใน TextField คำสั่ง onChanged จะทำงานและเก็บข้อมูลที่กรอกเข้ามาให้กับตัวแปร name ด้วยคำสั่ง setState และนำตัวแปร name ไปกำหนดไว้ที่ Text เมื่อ state name มีการเปลี่ยนแปลงค่าที่แสดงผลที่ Text ก็จะเปลี่ยนแปลงตามการใส่ข้อมูลที่ TextField

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var name = "";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('My App'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              TextField(
                onChanged: (value) {
                  setState(() {
                    name = value;
                    name = "สวัสดีคุณ $name";
                  });
                },
              ),
              const SizedBox(
                height: 8,
              ),
              Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    name.toString(),
                  )),
            ],
          ),
        ));
  }
}
แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ