본문 바로가기

Flutter

[Flutter] Stateful Widget vs Stateless Widget 차이

안녕하세요. 메로나입니다.

 

오늘은 Flutter를 접하면서 Stateful이 상속된 class와 Stateless가 상속된 class를 본 적이 있을 겁니다.

어떤 역할을 하는지 / 어떤 차이점이 있는지 공부하겠습니다.

 

Stateful Widget이란?
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
  • 예제 코드에 보이시는 StatefulWidget이 상속된 class는 state가 변경될 때마다 UI를 다시 그려줄 수 있습니다.
  • 예를 들어 축구 게임의 경우 점수를 나타내는 위젯은 골이 들어갈 때마다 점수를 수정해줘야 하므로 Stateful widget이 적절합니다.

 

Stateless Widget이란?
import 'package:flutter/material.dart';

//This function triggers the build process
void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: const Color.fromARGB(255, 230, 255, 201),
        appBar: AppBar(
          leading: const Icon(Icons.menu),
          backgroundColor: Colors.green,
          title: const Text(
            "GeeksforGeeks",
            textAlign: TextAlign.start,
          ),
        ), // AppBar
        body: const Center(
          child: Text(
            "Stateless Widget",
            style: TextStyle(color: Colors.black, fontSize: 30),
          ),
        ), // Container
      ), // Scaffold
    ); // MaterialApp
  }
}
  • 화면이 한 번 로드되면 변경될 Data가 없는 것을 의미합니다.
  • 예를 들어 앱 이름, 앱 가이드 등등 로드 시 변하지 않는 값들을 의미합니다.

 

Stateful Widget만 사용하면 되지 않을까?

저는 두 가지를 공부하고 widget을 만들 때 Stateful Widget만 사용하면 편할 것 같다는 생각이 들었습니다.

  • Stateless보다 Stateful이 더 무겁습니다. 그래서 두 가지를 적절한 곳에 사용해야합니다.
  • 코드 유지보수가 어렵습니다. 상태 관리는 생각보다 어렵습니다. 전부 Stateful로 만들어버리면 코드가 난잡해지기 쉽습니다.
  • flutter는 reactive UI 프레임워크로 상태와 UI를 분리하고 필요할 때만 상태를 업데이트하도록 설계되어 있습니다.

 

참고문헌

https://itwise.tistory.com/29

 

플러터 - Stateless Widget과 Stateful Widget 차이점

한창 앱 개발이 진행 중이지만 개인적으로 플러터 공부에 대해 정리도 하고 쉬어가는 의미로 Stateless와 Stateful 차이점에 대해 포스팅한다. ​ Stateless Widget 화면이 로드될 때 한 번만 그려지는 Stat

itwise.tistory.com

https://www.geeksforgeeks.org/flutter-stateful-vs-stateless-widgets/?ref=ml_lbp

 

Flutter - Stateful vs Stateless Widgets - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

'Flutter' 카테고리의 다른 글

[Flutter] 서버와 통신하는 방법  (0) 2025.05.10
[Flutter] 라이센스 중요성  (0) 2025.02.13
[Flutter] Flutter Navigation  (0) 2025.01.28
[Flutter] pubspec.yaml  (0) 2025.01.27
[Flutter] Flutter의 Widget Lifecycle  (0) 2025.01.19