Flutter Mobile Development · บทเรียน

วิดเจ็ต Stateless และ Stateful

ทำความเข้าใจความแตกต่างหลักระหว่าง StatelessWidget และ StatefulWidget พร้อมเรียนรู้ว่าเมื่อใดและอย่างไรจึงควรใช้แต่ละแบบเพื่อสร้างส่วนติดต่อผู้ใช้แบบไดนามิก

บทเรียน 1 จาก 411 ขั้นตอน

วิดเจ็ต Stateless และ Stateful เป็นบทเรียน Flutter Mobile Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Flutter Mobile Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Widgets: The Building Blocks

Flutter UIs are built entirely from widgets. Think of them as LEGO bricks! Everything you see on screen – text, buttons, even layout containers — is a widget.

Widgets describe how your app's UI should look given its current configuration and state. There are two main types of widgets you'll encounter:

  • StatelessWidget
  • StatefulWidget

StatelessWidget: Static UI

A StatelessWidget is a widget that does not change its appearance or behavior over time. Once it's built, it stays the same.

  • It doesn't have any internal "state" to manage.
  • Its properties are immutable (cannot be changed after creation).
  • It's perfect for displaying static content like text, icons, or images that don't need to react to user input or data changes.

Simple StatelessWidget

Here's a basic StatelessWidget that displays a welcome message. Notice how its content is fixed.

Run this code to see a static "Hello, CoddyKit!" message.

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(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Stateless Demo'),
        ),
        body: const Center(
          child: Text(
            'Hello, CoddyKit!',
            style: TextStyle(fontSize: 24),
          ),
        ),
      ),
    );
  }
}

When to Go Stateless

Use a StatelessWidget when:

  • The widget's appearance depends only on its own configuration parameters (passed in its constructor).
  • It doesn't need to respond to user interactions (like taps) or internal data changes.
  • Examples: Text, Icon, Image, AppBar, Padding, Row, Column.

These widgets are efficient because Flutter doesn't need to rebuild them if their parent changes, unless their properties explicitly change.

StatefulWidget: Dynamic UI

A StatefulWidget is a widget that can change its appearance and behavior over time, reacting to user input or data changes.

  • It has internal "state" that can be modified.
  • When its state changes, the widget rebuilds to reflect the new state.
  • It's perfect for interactive elements like checkboxes, sliders, or dynamic lists.

Updating UI with setState()

To make a StatefulWidget dynamic, you modify its internal state. When the state changes, you must call the setState() method.

Calling setState() tells Flutter that the internal state of this widget has changed, and it needs to rebuild the UI to reflect the new state.

Without setState(), your state might change, but the UI won't update!

Interactive StatefulWidget

Let's build a simple counter app using a StatefulWidget. Tap the button to increment the number.

Observe how setState() is used to update the _counter variable and rebuild the UI.

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(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Stateful Demo'),
        ),
        body: const Center(
          child: CounterWidget(),
        ),
      ),
    );
  }
}

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

  @override
  State<CounterWidget> createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _counter = 0; // This is the mutable state

  void _incrementCounter() {
    setState(() {
      _counter++; // Update state
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          'Count: $_counter',
          style: const TextStyle(fontSize: 32),
        ),
        const SizedBox(height: 20),
        ElevatedButton(
          onPressed: _incrementCounter,
          child: const Text('Increment'),
        ),
      ],
    );
  }
}

StatefulWidget's Journey

StatefulWidgets go through a lifecycle. Key moments include:

  • createState(): Creates the mutable state object.
  • initState(): Called once when the widget is inserted into the widget tree. Good for one-time setup.
  • build(): Called every time the widget needs to display its UI, typically after setState().
  • dispose(): Called when the widget is removed from the tree. Good for cleaning up resources.

Understanding these helps manage complex interactions.

Choosing the Right Widget

Here's a quick comparison to help you decide:

  • StatelessWidget:
    • Immutable properties.
    • Doesn't change after creation.
    • No internal state.
    • Efficient for static content.
  • StatefulWidget:
    • Mutable state (managed by a `State` object).
    • Can change dynamically.
    • Responds to user interaction/data.
    • Uses setState() to trigger rebuilds.

Most widgets start as stateless; only make them stateful if they truly need to change dynamically.

Widget Type Challenge

You are building a Flutter app. Which type of widget would you primarily use for a simple icon that, when tapped, changes its color?

Recap: Dynamic vs. Static

Great job! You've learned the fundamental difference between StatelessWidget and StatefulWidget.

  • StatelessWidgets are for static UI elements that don't change after they're built.
  • StatefulWidgets are for dynamic UI elements that need to react to interactions or data changes, using setState() to update their appearance.

Choosing the right widget type is crucial for building efficient and maintainable Flutter applications. In the next lesson, we'll dive into basic layout widgets!

เริ่มต้นได้ฟรี

เรียนรู้ Dart ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
22
บทเรียน
88

คำถามที่พบบ่อย

บทเรียน “วิดเจ็ต Stateless และ Stateful” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “วิดเจ็ต Stateless และ Stateful” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Flutter Mobile Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “วิดเจ็ต Stateless และ Stateful”

ทำความเข้าใจความแตกต่างหลักระหว่าง StatelessWidget และ StatefulWidget พร้อมเรียนรู้ว่าเมื่อใดและอย่างไรจึงควรใช้แต่ละแบบเพื่อสร้างส่วนติดต่อผู้ใช้แบบไดนามิก คุณปฏิบัติ Flutter Mobile Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Flutter Mobile Development หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Flutter Mobile Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “วิดเจ็ต Stateless และ Stateful” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Flutter Mobile Development นี้ได้ไหม

ได้ บทเรียน Flutter Mobile Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. วิดเจ็ต Stateless และ Stateful
  2. วิดเจ็ตการจัดวางพื้นฐาน
  3. องค์ประกอบส่วนติดต่อผู้ใช้แบบโต้ตอบ
  4. การสร้างรายการเลื่อนได้ด้วย ListView
← กลับไปที่ Flutter Mobile Development