변하지 않는 속성을 가진 위젯
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
statelessWidget을 클래스에서 상속받아 bulid() 함수를 override해서 사용해야한다. 이 bulid()함수를 통해 위젯을 생성하게 된다. 변하지않는 속성을 가진 위젯을 정의 할 때 사용한다.
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
StatefulWidget은 StatelessWidget과 반대로 모양과 작동을 변경할 수 있는 위젯이다. 즉 State에 따라 위젯을 변경하도록 도와준다. 클래스 내의 필드는 항상 final로 표시되며, 오버라이드를 통해 상속받은 createState() 함수를 재정의 한다.
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title), //Widget통해 접근
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
state는 런타임 동안 사용자의 상호작용으로 인한 데이터 변경에 따라 위젯을 변경을 해주는 데 도움을 준다.
여기서 Scaffold 위젯을 사용하는 데 이것은 머트리얼 디자인 앱을 만들 때 사용되는 되는 위젯이다. 이 예제는 appBar, body, floatingActionButton으로 구성되어있다.

화면 상단에 고정되어 있는 appbar와 화면의 내용을 담은 boby, '+'버튼인 플로팅 액션 버튼을 확인할 수 있다.
이런 Scaffold와 같은 미리 지정된 위젯을 잘 활용하면 편리하게 UI 개발을 진행할 수 있다.
widget들은 tree 구조로 정리될 수 있으며 한 widget내에 얼마든지 다른 widget들이 포함될 수 있다. widget은 부모 위젯과 자식 위젯으로 구성되며, parent widget을 widget container라고 부르기도 한다.