๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿฅ– Bread Basics/Flutter

[Flutter] StatefulWidget:: ํ™”๋ฉด, ๋ฐ์ดํ„ฐ, ๋กœ์ง์„ ํ•œ ๋ฒˆ์—

by BreadDev 2025. 6. 27.
728x90

Flutter ๊ฐœ๋ฐœ์„ ์‹œ์ž‘ํ•˜๋ฉด์„œ ๊ฐ€์žฅ ๋จผ์ € ๋งŒ๋‚˜๊ฒŒ ๋˜๋Š” ๊ฒƒ ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋ฐ”๋กœ StatefulWidget์ž…๋‹ˆ๋‹ค. ๊ฐ„๋‹จํ•œ ์นด์šดํ„ฐ ์•ฑ์„ ๋งŒ๋“ค๋ฉด์„œ "์™œ ์ด๋ ‡๊ฒŒ ๋ณต์žกํ•˜๊ฒŒ ๋‘ ๊ฐœ์˜ ํด๋ž˜์Šค๋กœ ๋‚˜๋‰˜์–ด์ ธ ์žˆ์„๊นŒ?" ๊ถ๊ธˆํ•ดํ•˜์‹  ์  ์žˆ์œผ์‹ ๊ฐ€์š”? 

StatefulWidget์ด๋ž€ ๋ฌด์—‡์ธ๊ฐ€?

StatefulWidget์€ ๋ณ€๊ฒฝ ๊ฐ€๋Šฅํ•œ ์ƒํƒœ๋ฅผ ๊ฐ€์ง€๋Š” ์œ„์ ฏ์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์—ฌ๊ธฐ์„œ ์ค‘์š”ํ•œ ํฌ์ธํŠธ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

// StatefulWidget ํด๋ž˜์Šค ์ž์ฒด๋Š” ๋ถˆ๋ณ€(immutable)!
class StateCounterHomePage extends StatefulWidget {
  const StateCounterHomePage({super.key});

  @override
  State<StateCounterHomePage> createState() => _StateCounterHomePageState();
}

// ์‹ค์ œ ์ƒํƒœ๋Š” State ํด๋ž˜์Šค๊ฐ€ ๊ด€๋ฆฌ
class _StateCounterHomePageState extends State<StateCounterHomePage> {
  int count = 0; // ์ด๊ฒƒ์ด ์ง„์งœ ์ƒํƒœ!
  
  @override
  Widget build(BuildContext context) {
    // UI ๊ตฌ์„ฑ
  }
}

StatefulWidget = ์œ„์ ฏ ํŒฉํ† ๋ฆฌ State = ์‹ค์ œ ์ƒํƒœ + UI + ๋กœ์ง

์‹ค์ œ ์ฝ”๋“œ๋กœ ๋ถ„์„ํ•ด๋ณด๊ธฐ

์นด์šดํ„ฐ ์•ฑ์„ ํ†ตํ•ด StatefulWidget์˜ ๊ตฌ์กฐ๋ฅผ ์ž์„ธํžˆ ์‚ดํŽด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

class _StateCounterHomePageState extends State<StateCounterHomePage> {
  // ๋ฐ์ดํ„ฐ (์ƒํƒœ)
  int count = 0;

  @override
  Widget build(BuildContext context) {
    // ํ™”๋ฉด (UI)
    return Scaffold(
      appBar: AppBar(title: Text('State Counter App')),
      body: SafeArea(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            spacing: 10,
            children: [
              Text(
                'Counter.count : ${count}',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 30),
              ),
              ElevatedButton(
                // ๋กœ์ง (์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ)
                onPressed: () {
                  setState(() {
                    count = count + 1;
                  });
                },
                child: Text('์นด์šดํŠธ ์ฆ๊ฐ€'),
              ),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    count = count - 1;
                  });
                },
                child: Text('์นด์šดํŠธ ๊ฐ์†Œ'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

StatefulWidget์€ ์„ธ ๊ฐ€์ง€ ์ฑ…์ž„์ด ํ•œ ๊ณณ์— ์žˆ์Šต๋‹ˆ๋‹ค

  1. ๋ฐ์ดํ„ฐ: int count = 0 - ์œ„์ ฏ์˜ ์ƒํƒœ
  2. ํ™”๋ฉด: build() ๋ฉ”์„œ๋“œ - UI ๊ตฌ์„ฑ
  3. ๋กœ์ง: onPressed ์ฝœ๋ฐฑ - ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ ๋ฐ ์ƒํƒœ ๋ณ€๊ฒฝ